Reputation: 5051
I have SAS date objects stored as integer and they look like : 19725
.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1 04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06
and not 2003-06-04
as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Upvotes: 2
Views: 926
Reputation: 8767
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);
Upvotes: 3
Reputation: 63424
In addition to RC's point about starting the month correctly with Calendar.JANUARY
, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD'
is day of year (so 340th day of the year is Dec 6). 'dd'
is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy'
also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY'
is "Week Year", which in some cases may differ from yyyy
(calendar year) near the end of the year. See the docs for more details.
Upvotes: 3
Reputation:
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
Upvotes: 3