Search code examples
androiddatemilliseconds

Android Date worng conversion date into millis


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


Solution

  • 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