cancel
Showing results for 
Search instead for 
Did you mean: 

Simple question - How to find date

Former Member
0 Kudos

Hi Experts,

I have a simple question on date. Suppose today is Jan 4, 2010. I have to find out Jan 1, 2007 using Java code.

I have used following code. This code will work for 2010 and 2011 properly. However it won't work properly after Feb 28, 2012. Please see "dayInMillis*1096 " portion of code. Here 365365366 = 1096.

How I can avoid this hard coding. Do we have any simple way to get Jan 1, 2007 even without using following code.

	Calendar calendar = Calendar.getInstance();
	int lastDate = calendar.getActualMaximum(Calendar.DATE);
	int firstDate = calendar.getActualMinimum(Calendar.DATE);
	int todayDate = calendar.get(Calendar.DATE);
	int dayofyear = calendar.get(Calendar.DAY_OF_YEAR);
		
	java.sql.Date currentdate = new java.sql.Date(System.currentTimeMillis());
	long dayInMillis = 1000 * 60 * 60 *24; //1 day
	wdContext.currentContextElement().setFromDate(new Date(System.currentTimeMillis() - dayInMillis*1096 - ((dayofyear-1)*dayInMillis)));

Please help.

Regards,

Gary

Accepted Solutions (1)

Accepted Solutions (1)

siarhei_pisarenka3
Active Contributor
0 Kudos

Hi Gary

Everything is simpler...

Calendar calendar = Calendar.getInstance();
calendar.set(2007, 0, 01);   // 0 means Jan
java.sql.Date yourRequiredDate = new Date(calendar.getTimeInMillis());
wdContext.currentContextElement().setFromDate(yourRequiredDate);

BR, Siarhei

Former Member
0 Kudos

Hi Siarhei,

Thanks.

Calendar calendar = Calendar.getInstance();
calendar.set(2007, 0, 01);   // 0 means Jan
java.sql.Date yourRequiredDate = new Date(calendar.getTimeInMillis());
wdContext.currentContextElement().setFromDate(yourRequiredDate);

Here we have hardcoded 2007. We don't want to hardcode. We have to calculate it current year - 3 years.

Pls help.

Regards,

Gary

siarhei_pisarenka3
Active Contributor
0 Kudos

>We don't want to hardcode. We have to calculate it current year - 3 years.

Then change the code above with the following:

calendar.set(calendar.get(Calendar.YEAR) - 3, 0, 01);   // 0 means Jan

BR, Siarhei

Answers (1)

Answers (1)

Former Member
0 Kudos

Hi Gary,

I am not pretty much clear with your question, whatever i have understood, i have found a way to get the previous date given the current date.

Below is the code for the same.

Calendar now = Calendar.getInstance();//Jan 4, 2010

String nowDateStr = DateFormat.getDateInstance().format(now.getTime());

System.out.println("date now : " +nowDateStr);

now.add(Calendar.YEAR, -3);//2007

now.add(Calendar.DATE, -3);//1st

now.add(Calendar.MONTH, 0);//No change in month, Jan.

String changedDateStr = DateFormat.getDateInstance().format(now.getTime());

System.out.println("date changed : " +changedDateStr);