Android Date worng conversion date into millis

104 views Asked by At

I got such an issue. I save a Date (yyyy,mm,dd). From this date I need to get its millisec representation, but when I call getTime() it gives me wrong time. Where is the issue?

Example :        
Date testDate= new Date (2015,5,11);

When I try to call this date millisec, testDate.getTime()

result=61392117600000, but it must be result=1433970000000

Note : 5 means Jun, because it counts from 0

2

There are 2 answers

0
Giru Bhai On BEST ANSWER

Because in the Date Class under package java.util; the date method add year from 1900 as

/**
 * Constructs a new {@code Date} initialized to midnight in the default {@code TimeZone} on
 * the specified date.
 *
 * @param year
 *            the year, 0 is 1900.
 * @param month
 *            the month, 0 - 11.
 * @param day
 *            the day of the month, 1 - 31.
 *
 * @deprecated Use {@link GregorianCalendar#GregorianCalendar(int, int, int)} instead.
 */
@Deprecated
public Date(int year, int month, int day) {
    GregorianCalendar cal = new GregorianCalendar(false);
    cal.set(1900 + year, month, day);
    milliseconds = cal.getTimeInMillis();
}

So you need to change

Date testDate= new Date (2015,5,11);

to

Date testDate= new Date (115,5,11);

Recommended way is to use SimpleDateFormat as given below.

Android convert date and time to milliseconds

0
Maximosaic On

year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)

From JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html)

Therefore instead of year 2015 you would use 2015 - 1900 = 115 as your year parameter