0

Below code in India returns "1970-01-01" for 0L and in Canada it returns "1969-12-31". I have no clue what is going wrong here, Can anyone tell me what is the problem here. I suspect it is because of timezone issue but need more information on it.

public static RestEDate convertLongDateToStringDate(long lDate) {
    String returnDate = "";
    if (lDate >= 0) {
        returnDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(lDate));
    }
    return new RestEDate(returnDate);
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Elon
  • 29
  • 4

2 Answers2

5

Yes, it's a timezone issue. Your SimpleDateFormat instance is defaulting to the current timezone. Midnight Jan 1st 1970 GMT (which is what 0L means) is 19:00 Dec 31st, 1969 on the east coast of Canada (GMT-0500) and 16:00 Dec 31st, 1969 on the west coast of Canada (GMT-0800). The Date instance is correct, but how that's interpreted depends on what timezone your formatter is using.

To set the timezone used by SimpleDateFormat (for instance, to GMT), use its setTimeZone method (or setCalendar if you already have a Calendar around you want to use).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The answer by T.J. Crowder is correct.

Joda-Time || java.time > java.util.Date

Better to use either the Joda-Time library or the similar java.time package built into Java 8. Either is vastly superior to the mess that is the java.util.Date and .Calendar classes.

Assign Time Zone

In both of these libraries, a date-time object knows it's own assigned time zone. If not specified, the JVM’s default time zone is applied. Better to specify the desired time zone rather than rely implicitly on default.

Use proper time zone names. Avoid the common 3 or 4 letter codes which are neither standardized nor unique.

In the example below, Montréal is five hours behind UTC.

Joda-Time Example

Here is a Joda-Time 2.6 example.

DateTimeZone zoneMontreal = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeZeroInMontreal = new DateTime( 0L, zoneMontreal );
DateTime dateTimeZeroInUtc = dateTimeZeroInMontreal.withZone( DateTimeZone.UTC );  

When run.

dateTimeZeroInMontreal : 1969-12-31T19:00:00.000-05:00
dateTimeZeroInUtc : 1970-01-01T00:00:00.000Z
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154