Reputation: 401
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.
Upvotes: 0
Views: 1303
Reputation: 350147
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.
Upvotes: 3
Reputation: 338406
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
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
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.
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.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.
Upvotes: 0