Numbers and dates
※ Download: Javascript date to iso string
Firefox Full support 29 IE Full support 11 Opera Full support 15 Safari Full support 10 WebView Android No support No Chrome Android Full support 26 Edge Mobile? Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. Firefox Android No support No Opera Android? Values from 0 to 99 map to the years 1900 to 1999.
Sets the milliseconds for a specified date according to local time. Firefox Full support 52 IE? Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized. Expect poor cross-browser support.
Date.parse() - Firefox Android Full support 56 Opera Android No support No Safari iOS Full support 10 Samsung Internet Android Full support Yes nodejs? JSON has become a rather prevalent serialization format in recent years.
JSON has become a rather prevalent serialization format in recent years. The code and small support library discussed in this post is up on , so you can download and play around with this yourself. I find this functionality indispensable and use as part of my own libraries in just about every client-side application that uses AJAX. Which seems like a rather major omission given that dates are pretty important in computing and business environments. So in order to represent dates in JavaScript, JSON uses a specific string format — — to encode dates as string. Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized. NET Web API, Nancy, ServiceStack etc. This is because the JSON created is in fact a string and JSON. Decoding the Date The good news — and maybe not very widely known news at that — is that ISO dates can be easily converted into JavaScript dates by use of the flexible JavaScript Date constructor. The date constructor accepts a wide variety of inputs to construct a date, ISO 8601 amongst them. JSON strings would have to remove the wrapping quotes in order to parse by the new Date constructor. It works, but you have to be careful in your usage of these pseudo date strings, always remembering that they have to be converted manually when you use them. JSON Parser Extensions One way around this date problem is to extend the JSON parser to automatically convert the ISO string dates into real JavaScript dates. We can check each of the key value pairs for each property as its parsed and look for strings that look like dates and automatically transform them into dates. Using this date parser you can now add that to the call to JSON. If you have an array of these objects — all the dates are still converted. This much better but still limited in that you have to manually call JSON. Most likely JSON is parsed for you by a library of some sort like jQuery, or AngularJs or any other framework. In that case you have no control over the JSON parsing because the parsing happens deeply buried inside of a framework. The common denominator here is the JSON parser itself. What if we can just take over the parser? What if we could — at the beginning of the page perhaps — override the JSON parser to actually use our behavior instead of the stock behavior? To do this we can create a few additional functions and provide for a way to switch the parser: if this. Returns all dates as real JavaScript dates. We can then create a. By replacing the JSON. To use this you would call JSON. Entered: Wed Jan 01 2014 13:34:56 GMT-1000 Hawaiian Standard Time result. Updated: Wed Jan 03 2014 23:28:56 GMT-1000 Hawaiian Standard Time The latter creates real dates. As will any other framework that uses the native JSON parsers in JavaScript. This means that by replacing the JSON. In effect, the date parsing support is now global. Because the setting is page or scope global, you can also reset the original parser by using: JSON. Caveats of overriding JSON Parsing There are a couple of caveats to doing a wholesale behavior change like this to the JSON parser. First you are in fact changing behavior when you apply this parser and if there is existing code that relies on the existing date ISO format of dates, that will of course cause problems. The other caveat of a JSON parse filter is that it is a filter and it slows down JSON parsing. Do you really need Dates? Native JavaScript date formatting sucks unless you add yet another library is a good one to your page, and you have all the tools necessary to format dates easily on your server. Rather than pushing down date values to the client consider pushing preformatted date strings in your ViewModels. This alone will reduce date usage significantly on the client. NET parser understands a lot of different date formats including human readable ones and can parse that out of JSON when you push your dates back up to the server using ASP. NET Web API or ASP. With the advent of purely client side SPA style applications this is getting more common now, but often this still can be addressed via server side formatting. If you can avoid parsing dates on the client, avoid it and format on the server. Sometimes Dates are necessary That leaves real date requirements on the client where the client has to actively work and manipulate dates and for those cases real JSON date parsing is highly useful. It seems silly to actually having this discussion. A serializer without date formatting support just seems… silly, if you really think about it. But then this is JavaScript and there are lots of things that are just plain silly. If you do need to get dates into the client and if you actually send dates from the server, then a global way of date deserialization certainly makes life a lot easier than having to manually translate dates at every usage point in your front end code. And for that these routines I described here have been very useful to me. I hope some of you get some utility out of them as well. NET generate JSON dates with the Z UTC designation which should fix the timezone issue pretty easily, as long as your code knows how to properly deal with UTC dates. Personally I keep all dates in UTC format and convert to local time when needed only which seems easiest all around. Bertrand - yes that's an issue, but a pretty unlikely one. I just can't think of a use case where you'd actually have ISO dates or something that looks very similar as to match the RegEx as a string value. IAC, if you really needed to do that, then use the regular parser on the page and resort to manually parse the encoded dates on use. But again I can't think of a use case where this would happen and personally I'd be more than happy to live with that infinitesimally small risk. Server-side we always use Utc dates, and in the current project I'm in, I decided to push Utc dates to the client as well. Previously we'd convert dates in the controllers when binding data to poco models. I went with moment. For example we can show the local time at a branch office, or events that are specific to another users timezone while simultaneously displaying data such as when a record may have been updated, but relative to the user. I came across moment. Adding a simple js timer to update the document once a minute so that relative changes age as you sit and watch instead of being just a conversion when you first navigated. It makes the MVC models much simpler as there are never any timezone conversions. It's important to note in JavaScript dates are always internally in UTC, and to be honest, when using moment. The biggest problem I'm facing is that what you're calling a date is actually a time. A date is the thing calendars mark off. Representing dates with times is a big pain. It seems like we just can't win. Postgres gets this right. But then the libraries I use get it wrong. So either I change the libraries, write a bunch of pointless and error prone code, or change my database schema and write a bunch of pointless and error prone code to group times by the date part. I especially like the fact that you stress the common-sense approach of avoiding client-side date parsing whenever possible! We have converted to using the DateTimeOffset data type in all our serverside database and. It gives the best of both worlds - local time when you need it and UTC when you don't. We actuallt use DATETIMEOFFSET 0 in the database. This gives the precision we need in the same 8 bytes of storage as a UTC DATETIME. Also, thanks for the link to moment. The only thing we're sure of, is that the 10 first characters are yyyy-mm-dd. There is 3 different cases we need to handle. To prevent it, we need to substr y-m-d from the string, and use new Date y,m,d,0,0,0,0. Case 3 will work, and return data like case 2 do. It works fine for now with all different API we're connecting to. Yes, there is certainly some performance issues of all these substring... Interesting and very informative! Wondering if it would make sense to write up an example that could be used as a directive in AngularJS? Seems to me that if it really only effects the Small world. I did FoxPro development for many years and the last time I touched it was probably 15 years ago. I know manage a couple of Java teams and was Googling JSON date parsing and look who I run across, Rick Strahl. Doubtful you would remember me, but it's good to see you are still alive and kicking. Thanks for this informative post. Currently I am working on an application and I need to pass Java 8 LocalDate from MVC controller to Ajax response in Jquery Data tables. I did not find anything to deserialize Localdate JSON string back to LocalDate in UI. So I manually had to append year, month and day to build date. Is there a better way to handle Localdates in such siituation. Please let e know, I will get rid of messy code in JS file I wrote. For example, given time zone and valid local time instant in that time zone you can calculate offset from UTC but you cannot infer time zone from ISO 8601 date with some offset. Different time zones may have same UTC offset for many reasons daylight saving time. Same time zone at different time instants may have different offset from UTC. I think this is an elegant solution. I really like the advice to just avoid dates in the first place. In addition to preventing a large class of errors, using server formatted strings also makes client side databinding code simpler and staves off any temptation to write god awful, stateful and logic-ridden models. Today I had to post a javascript datetime to C controller. All these historical information is enclosed by the timezone, and they're not supported by ISO8601, AFAIK. Today however I came across runtime error that is originating from json. Returns all dates as real JavaScript dates. From studying the code it seems this parameter should be a function, but something is calling this function and passing a number for chainFilter. This is causing the runtime error. I notice in this blog post, you don't mention the chainFilter parameter. What does this parameter do and is needed? Is it supposed to be the equivalent of the reviver function on the default JSON. Thank you David David - you need to find whatever is calling the routine with a number. The code isn't breaking inside of this function it's breaking inside of the API, which expects a function and is likely trying to execute the number which fails. There's likely another filter attached to the JSON parsing chain that's causing this to happen. You should be able to look at the call stack when you see the number and see where it's being called from. Hopefully it's externally tracable code and not internal traces. Hi Rick, Thanks a lot for your help. I'm using Angular 6 and the grid component from Telerik Kendo UI for Angular. It seems the Telerik grid component is doing something unexpected with the JSON parser and that is clashing with the json. Moreover if there's anything JavaScript taught us, it's that you probably shouldn't silently coerce types based on their content. It won't do it automatically, but it will make it a lot more convenient. If conversion has already happened, nothing more happens. If conversion has not happened, it happens. Having said that, I'm half-inclined to just go back to xmlrpc. At least it de- serialized dates without intervention.
I have a date string in ISO format, like 2014-11-03T19:38:34. I am trying to convert Twitter datetime to a local iso-string for prettyDate now for 2 days. Updated: Wed Jan 03 2014 23:28:56 GMT-1000 Hawaiian Standard Time The latter creates real dates. A date is the thing calendars mark off. NET generate JSON dates with the Z UTC designation which should fix the timezone issue pretty easily, as long as your code knows how to properly deal with UTC dates. Since there are a couple different ways to achieve this, I've listed them in order of my personal preference. We have converted to using the DateTimeOffset data type in all our serverside database and.