Why do IE/FF and Chrome javascript engines differ on how to interpret this Date format (YYYY-MM-DDTHH:mm:ss.fff) without the timezone designator?
new Date("2015-02-18T15:43:57.803").getUTCHours()
UTC Hours
Chrome: 15
IE11/FF: 21
I don't understand this - is it because Chrome assumes it's local whereas IE/FF assume it's UTC? This seems like a Chrome bug.
Interestingly - appending a "Z" to the end of the string tells both Chrome and IE/FF that the time is UTC and they can agree. Has anyone else noticed this javascript implementation discrepancy with Date?
new Date("2015-02-18T15:43:57.803Z").getUTCHours()
UTC Hours
Chrome: 15
IE11/FF: 15
Ultimately - this is the result of the out-of-box serializer for ASP.NET Web API, which I thought used JSON.NET, but now appears to be internal where JSON.NET uses IsoDateTimeConverter.
Checking GlobalConfiguration.Configuration.Formatters.JsonFormatter tells me we're using JsonMediaTypeFormatter. Is Web API not using JSON.NET serializer out of the box?
This is a boon for Web API people - at least back in ASP.NET MVC we had a consistent date format (albeit proprietary - /Date(number of ticks)/) via the JavascriptSerializer
ES5 says that ISO 8601 format dates without a time zone should be treated as local(that interpretation has since been revised), but the ed. 6 draft says to treat them as UTC. Some script engines have implemented ed. 6, some ES5 and the rest neither.
The ed. 6 (and later) aren't consistent with the ISO 8601 specification.
The bottom line is don't use Date.parse (or pass strings to the Date constructor), manually parse date strings.
For us, the crux of this issue is that DateTimeStyles.RoundtripKind only works if your DateTime properties set the DateTime.DateTimeKind (other than DateTimeKind.Unspecified - the default) or better yet - using DateTimeOffset which enforces use of the TimeZone specificity.
Since we already had DateTime class properties, we worked around this for now by assigning the JsonSerializerSettings.DateTimeZoneHandling from DateTimeZoneHandling.RoundtripKind (DateTime default) to DateTimeZoneHandling.Utc in our Global.asax.cs. This change essentially appends the "Z" to the end of the DateTime - however there is one more step to convert the Local time to UTC.
The second step is to provide the offset by assigning IsoDateTimeConverter.DateTimeStyles which JSON.NET JsonSerializer will pickup from a SerializerSettings.Converters and automatically convert from Local time to UTC - much like the out-of-the-box ASP.NET MVC does.
Obviously - there are other options, but this is solution worked for us.
Global.asax.cs
protected void Application_Start() {
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AdjustToUniversal });
}
The reason this works is because RoundtripKind honors DateTime's DateTimeKind - which is Unspecified by default. We want to explicitly convert this to UTC - which JavaScriptSerializer used to do for us out of the box for ASP.NET MVC. The regional offset is provided by DateTimeStyles.AdjustToUniversal which converts your Local DateTime to UTC.
Related
I want to force clients (web, android, ios) to send the API only time in UTC/GMT.
This means that they get user's local time (using any method), convert it to UTC/GMT, and then send it to the API.
And I want to reject any datetime parameter that is not in UTC/GMT.
In JavaScript, I can get UTC this way:
new Date().toUTCString() which gives this result:
'Mon, 15 Nov 2021 04:26:38 GMT'
And I send this string to the API:
[HttpGet]
public object Parse(string clientDateTime)
{
var date = DateTime.Parse(clientDateTime);
return new
{
ParsedDate = date,
Kind = date.Kind.ToString()
};
}
However, I see that .NET parses this date time as Local and not as Utc. This is in spite of the string containing GMT.
How can I check the incoming datetime and make sure it's UTC/GMT?
You can greatly simplify your problem by using a conventional format for datetime serialization. A common choice for this problem is using the ISO 8601 datetime format.
Here you can find an in depth explanation of this format, but as an example this is a datetime in the ISO 8601 format: 2021-11-15T06:40:48.204Z (the final Z indicates that the datetime represented by this string is UTC)
The main advantage in fixing a format for date and times is that you will know in advance the format and you will be in a much better position to parse the datetime strings on the server.
Using the ISO 8601 format is a good choice, because it is a well known format and it is the standard de facto for the datetime serialization: this basically means that anyone writing a client for your application will be able to comply with the required format. Of course, you are required to clearly document this convention so that your clients (or your fellow developers) will be aware of it.
Another tip is using the DateTimeOffset struct instead of DateTime. DateTimeOffset is basically used to represent a specific point in time and that's exactly what you want: your clients will send you ISO 8601 strings representing a point in time and you want to know that point in time in your application.
Your clients will be able to use any time zone to express the point in time they want to send to your application. Doing this using an UTC datetime or any other time zone is just an implementation detail. Once you have parsed the datetime string to a DateTimeOffset instance, if you really want to, you can check whether it is an UTC time by checking the Offset property: it will be a zero TimeSpan value if the DateTimeOffset instance represents an UTC date and time.
In order to manipulate date in a Javascript client application I strongly suggest to use the Moment.js library. Check this docs to see how to get an ISO 8601 string with Moment.js
You can use this helper method to parse an ISO 8601 string to a DateTimeOffset instance. This implementation allows the client to send you a broad range of ISO 8601 compliant string formats, if you want you can be stricter by reducing the number of allowed formats (see the Iso8601Formats static field in the code).
To summarize:
ask your clients to only send you datetime strings in a format compliant with the ISO8601 specification. Clearly document this choice
for a Javascript client use a library like Moment.js to manipulate date and times. This will be much simpler than using plain old javascript Date objects.
if you are manipulating date time strings representing a specific point in time, use the DateTimeOffset struct instead of the DateTime struct. DateTimeOffset represents a specific point in time expressed in a certain time zone. The Offset property represents the difference between the point in time represented by the DateTimeOffset instance and UTC: its value will be a zero TimeSpan if the DateTimeOffset instance represents an UTC datetime. Notice that the point in time will always be the same regardless the time zone it is referring to, so using UTC doesn't make any real difference (it's just an implementation detail at this point).
use code like this one to parse a DateTimeOffset instance from a string. This code tries as many ISO 8601 compliant formats as possible (this is done in order to accept as many valid formats as possible). If you want, you can decide to be stricter: to do that, just reduce the number of formats in the Iso8601Formats array.
A final note on your code. The behaviour you are observing from DateTime.Parse is exactly the expected one. Check the documentation for DateTime.Parse:
Converts the string representation of a date and time to its DateTime
equivalent by using the conventions of the current thread culture.
DateTime.Parse is basically designed to use the locale settings of the machine running the code.
If you want to learn more on the difference between DateTime and DateTimeOffset you can check this stackoverflow question.
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.
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.
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
I've started using momentJs in an Angular/Typescript project. (Included incase it's relevant in any way although I very much doubt it)
In the run method of my module I call
moment.locale(window.navigator.language);
which correctly sets the locale to en-GB in my instance. Further down the line I use moment to parse a GB time.
when doing the following:
var mom = moment("24/11/2015 00:00:00");
for example. This populates a new moment object using the defaults set on the moment global (If i understand how it should work correctly). moms date is set to 2016-12-11T00:00:00.000Z. This clearly means it's parsed the given string in en-US instead of en-GB which was set via Locale in a default setting prior to this call. Is there anything I've missed in configuration/setup of moment which would make this not work?
I've also inspected the _locale property of my variable. mom._locale is set to en-gb and I can see the L,LL,LLL etc etc formats are all en-GB formatted values (as they should be).
running mom.toDate(); unsurprizingly returns the 2016 date stored internally by the moment object.
Some misc information I forgot to include:
I am using the latest release of momentjs from NuGet (Version 2.10.6 at time of writing) and I've included moment-with-locales.js in my HTML
Using any recent version of MomentJS, you should see why in the console:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Unless you specify a format string, MomentJS relies on the Date object's parsing, and unfortunately, regardless of locale the Date object will, with a string using /, assume U.S. format. One of the many, many things that aren't quite right with Date.
You'll need to use a format string, or supply the string in the simplified ISO-8601 format used by Date. From Parse > String:
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.
var day = moment("1995-12-25");
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
So I got around this by fetching the locale data from moment and just passing it into the format parameter. Considering the example input of "24/11/2015 00:00:00" I would structure my format as below:
var format = moment.localeData().longDateFormat('L') + " " + moment.localeData().longDateFormat("LTS");
this generates the format mask of "DD/MM/YYYY HH:mm:ss".
You can mix and match whatever formats you want and this will be locale specific to whatever you set moment.locale("") to be (presuming you have the locale information setup in moment already)
This is a crazy workaround and I'm surprised that moment doesn't presume locale information as default when parsing. TJCrowder has raised an issue on Github with the moment guys which I suggest anyone who cares should comment on. https://github.com/moment/moment/issues/2770
You're probably better off passing the format to moment directly and validating the string before hand. This will ultimately reduce the amount of debugging you'll need to do and get you up and running straight away.
var mom = moment("24/11/2015 00:00:00", "DD/MM/YYYY HH:mm:ss");
You could try the new(ish) Intl API but browser support is limited (IE11+), so I would recommend having a user select the month in a dropdown or something to force them to input a certain way.
I am using safari 8.0, And I try to do
new Date('sat-oct-10-2015');
on chrome the result is Date object with the right date. But on safari the result is
Invalid Date
how can I work with dates in this format in safari?
Do not use the Date constructor (or Date.parse) to parse strings. Until ES5, parsing of date strings was entirely implementation dependent. After that, the long form of ISO 8606 has been specified, however parts of that changed with ECMAScript 2015 so that even using specified formats is not consistent across browsers (e.g. 2015-10-15 12:00:00 may result in 3 different results in browsers currently in use).
The solution is to manually parse date strings, either write your own function (which is not difficult if you only need to support one format) or use a small library.
Always try to use the standard date format specified by ECMAScript ISO format.
Date.parse() i.e Date constructor will always produce the expected result if you use the standard string format. Also the browser may support additional string formats, but that may not be supported by all other browser vendors.
When creating a Date object with a “human-readable” string, you must use a certain format, usually conforming to RFC2822 or ISO 8601.
It may be that a browser is able to process your new Date('sat-oct-10-2015');, but this is not demanded by the specifications.
Hint: Look at some other ways to create a date object, for example with a Unix timestamp. This is easier and more reliable than the dateString approach.
I'd suggest using moment.js for dates in JavaScript. Then you can simply parse the date with
moment('sat-oct-10-2015', 'ddd-MMM-DD-YYYY').format();
moments API has good support in all major browsers and eases date manipulating and displaying with JavaScript.
I have a service that returns a date. The weird thing is that most of the time it comes back like this: /Date(1364227320000)/
but sometimes it returns the date like this /Date(1364050020139-0400)/
when I open up the visual studio debugger, the dates look the same for each one (minus differences in time)
What could account for this difference?
This is handled in System.Runtime.Serialization.Json.JsonWriterDelegator.WriteDateTimeInDefaultFormat(). If the DateTimeKind is Unspecified or Local, it adds the UtcOffset to the end (the -400 part, meaning Utc - 4 hours).
It depends on the kind of the DateTime object (i.e., the value of its Kind property). If you're returning a DateTime with DateTimeKind.Utc, there will be no offset. If the date time is of kind Local or Unspecified, the offset will be written out.
You can find more information about the format in the "DateTime Wire Format" section of the "Stand-Alone JSON Serialization" page on MSDN.