0

I'm facing an issue.

I'm saving the UTC time in my server using Java code:

DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");

I persist the time with this ->

time = timeFormat.format(new Date()).toString()

This is persisted as the UTC time.

Now, while displaying it in a browser, I convert it into local time :

var date = new Date(time);

convertToLocal(date).toLocaleString();

function convertToLocal(date) {
    var newDate = new Date(date.getTime() +date.getTimezoneOffset()*60*1000);

    var offset = date.getTimezoneOffset() / 60;
    var hours = date.getHours();

    newDate.setHours(hours - offset);

    return newDate;
}

console.log("Time : " + convertToLocal(date).toLocaleString())

This works fine in Chrome but in Firefox & IE , I get "Invalid Date" instead of the timestamp which I expect to see.

Please help.

pep8
  • 371
  • 3
  • 18
  • 2
    Browsers are not consistent in the date formats they accept beyond ISO standard (which yours isn't). – Pointy Nov 26 '18 at 14:54
  • 2
    I guess the Java output as string does not contain the `T` between date and time parts. Also make sure the timezone is added, which can be a plain "Z" suffix for UTC. Make sure it has that so it complies with [ISO standards](https://nl.wikipedia.org/wiki/ISO_8601). With that you wont need to add timezone offsets in JavaScript. Just use the appropriate rendering. – trincot Nov 26 '18 at 14:54
  • Also if send proper ISO UTC date string won't need to do local conversion – charlietfl Nov 26 '18 at 15:00
  • @trincot : Can you please explain with some snippets how I can modify the code? – pep8 Nov 26 '18 at 15:01
  • 1
    See https://stackoverflow.com/questions/20238280/date-in-to-utc-format-java for the change in Java code. Once that is done you only need to do `toLocaleString()` in JavaScript which will take the local timezone into account in the stringification. – trincot Nov 26 '18 at 15:12
  • It just doesn't work for IE or Firefox. I tried printing the console.log(date.toLocaleString) , but it doesn't print anything for IE or Firefox. Works fine in Chrome. Any suggestions? – pep8 Nov 26 '18 at 18:04
  • @trincot Thanks that worked, I wasn't building my code properly earlier. +1 – pep8 Nov 26 '18 at 20:24
  • OK, I posted this as an answer ,-) – trincot Nov 26 '18 at 20:34
  • You should't manipulate the value of the JS `Date` object to attempt to convert the time - that underlying millisecond since the epoch value should always be in UTC. To convert to local time, do that at _presentation_ time using the methods of the `Date` object designed for that purpose. – Alnitak Nov 26 '18 at 20:39
  • **Your Java code is incorrect.** That code does *not* produce text showing the moment in UTC. Its results are implicitly adjusted into the JVM’s current default time zone. See [my Answer](https://stackoverflow.com/a/53491319/642706) for details. – Basil Bourque Nov 27 '18 at 01:10

2 Answers2

3

The problem is that your Java code produces a date/time string that does not adhere to the ISO 8601 format. How a JavaScript engine must deal with that is not defined (and thus differs from one browser to another).

See How to get current moment in ISO 8601 format with date, hour, and minute? for how you can change the Java code to produce a date that uses the ISO format. You can just pass the desired format (ISO) to SimpleDateFormat and configure it to mean UTC:

DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

That output should look like 2018-11-26T19:41:48Z (several variations of this are accepted). Notice the "T" and terminating "Z" (for UTC).

Once that is done, JavaScript will correctly interpret the date/time as being specified in UTC time zone, and then you only need to do the following in JavaScript, without any need of explicitly adding time zone differences:

console.log("Time : " + date.toLocaleString())

JavaScript which will take the local time zone into account in the stringification.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • After formatting the date as per the answer shared, and then doing toLocaleString() , everything works fine. But I didn't have any "T" or "Z" in my date when I persisted it through java code with that format. Is that expected? Do I need to be worried ? – pep8 Nov 27 '18 at 07:00
  • For being 100% sure that JavaScript interprets the date string correctly, it would need to have that "T" and "Z". Just check the wikipedia page on what ISO 8601 specifies. If it complies with that, then every JavaScript engine will interpret it correctly. Other formats may work, but there is no language specification backing that up. – trincot Nov 27 '18 at 07:04
  • The answer you mentioned in the link , has this format in the accepted answer : "new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj)". And this doesn't contain a "T" or "Z" when you print a date with that format. – pep8 Nov 27 '18 at 07:10
  • Specify `yyyy-MM-dd'T'HH:mm:ss'Z'` as argument to `SimpleDateFormat`. I replaced the reference with a better Q&A on StackOverflow. – trincot Nov 27 '18 at 07:36
  • 1
    Yes, that is an issue, because with a string formatted as MM/dd/yyyy, JS cannot always determine with certainty whether the format of the received date string was MM/dd/yyyy or dd/MM/yyyy. It is not documented how JS should deal with this. It is always the safest to have yyyy-MM-dd. JS also supports [RFC 2822 compliant timestamps](https://tools.ietf.org/html/rfc2822#page-14), but there the day should come before(!) the month. – trincot Nov 27 '18 at 13:09
0

tl;dr

Use modern java.time classes, not terrible legacy classes.

Send a string in standard ISO 8601 format.

Instant
.now()
.truncatedTo(
    ChronoUnit.SECONDS
)
.toString()

Instant.now().toString(): 2018-11-27T00:57:25Z

Flawed code

This is persisted as the UTC time.

Nope, incorrect. You are not recording a moment in UTC.

DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");
String time = timeFormat.format(new Date()).toString() ;

You did specify a time zone in your SimpleDateFormat class. By default that class implicitly applies the JVM’s current default time zone. So the string generated will vary at runtime.

For example, here in my current default time zone of America/Los_Angeles it is not quite 5 PM. When I run that code, I get:

26-November-18 16:57:25

That is not UTC. UTC is several hours later, after midnight tomorrow, as shown next:

Instant.now().toString(): 2018-11-27T00:57:25.389849Z

If you want whole seconds, drop the fractional second by calling truncatedTo.

Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString(): 2018-11-27T00:57:25Z

java.time

You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant nowInUtc = Instant.now() ;  // Capture the current moment in UTC.

This Instant class is a basic building-block class of java.time. You can think of OffsetDateTime as an Instant plus a ZoneOffset. Likewise, you can think of ZonedDateTime as an Instant plus a ZoneId.

Never use LocalDateTime to track a moment, as it purposely lacks any concept of time zone or offset-from-UTC.

ISO 8601

As trincot stated in his correct Answer, date-time values are best exchanged as text in standard ISO 8601 format.

For a moment in UTC, that would be either:

  • 2018-11-27T00:57:25.389849Z where the Z on the end means UTC, and is pronounced “Zulu”.
  • 2018-11-27T00:57:25.389849+00:00 where the +00:00 means an offset from UTC of zero hours-minutes-seconds, or in other words, UTC itself.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154