javacalendartimestamp

Difference between date in miliseconds and its Calendar representation


I have two functions which convert a date String to a date in milliseconds:

public static long convertYYYYMMDDtoLong(String date) throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
    Date d = f.parse(date);
    long milliseconds = d.getTime();
    return milliseconds;
}

If I run this function I get the following result:

long timeStamp = convertYYYYMMDDtoLong("2014-02-17");
System.out.println(timeStamp);

It prints:

1389909720000

Now, if I run the following code:

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
System.out.println(cal.getTime());

It prints out:

Fri Jan 17 00:02:00 IST 2014

Why is my date shifted by one month? What is wrong?

P.S: My problem is that I need to map the date, represented as long, to another third party API which accepts Calendar format only.


Solution

  • You're using mm, which is minutes, not months. You want yyyy-MM-dd as your format string.

    It's not clear why you're not returning a Calendar directly from your method, mind you:

    private static final TimeZone UTC = TimeZone.getTimeZone("Etc/UTC")
    
    public static Calendar convertYYYYMMDDtoCalendar(String text) throws ParseException {        
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        format.setTimeZone(UTC);
        Calendar calendar = new GregorianCalendar(UTC);
        calendar.setDate(format.parse(text));
        return calendar;
    }
    

    (That's assuming you want a time zone of UTC... you'll need to decide that for yourself.)