0

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

reVerse
  • 35,075
  • 22
  • 89
  • 84
ask110593
  • 121
  • 1
  • 2
  • 9
  • It's no fun working with java `Date` objects. Maybe you want to consider working with JodaTime for example in your project: https://github.com/dlew/joda-time-android – Maximosaic Jun 19 '15 at 09:12

2 Answers2

1

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

Community
  • 1
  • 1
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
0

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

Maximosaic
  • 604
  • 6
  • 14