When designing a service that returns JSON to the browser (or server side JS), what is the "best" format for encoding dates in the resulting JSON response?
The data property should:
require as little or no parsing to convert to a Date() object
be sortable in the JSON representation itself
Returning the number of milliseconds since 1 January 1970 00:00:00 UTC seems like it would be the best option but is not particularly human readable when looking at the raw JSON.
What's preferred in your experience and why?
Personally I'd go with ISO 8601 (e.g. 2011-01-13T14:09Z).
It's well supported by virtually every programming language around, it's fairly easily human readable and, if you absolutely have to roll your own parser/formatter, it's fairly easy to deal with there too. It also has the sortable property you wanted.
Related
I'm using FormatJS library along with Handlebars to display a list of events that occured in the past. I'm calling for an endpoint on my server's REST API which returns me the list of events in Json, with datetimes to display for each event. ATM I'm saving datetimes in the DB using GMT time zone.
So when I'm getting my Json, I'm handling datetimes like this :
{{formatRelative commentDate}}
My issue is, since the datetimes are stocked in GMT, they display also like that. For example, since I'm on a GMT+2 timezone, as soon as a new event is created and shows up on the list, I see it "happened 2 hours ago" while it should be "a few seconds ago".
So, is there a way I can handle this ? Am I making a mistake in saving datetimes in GMT in my DB, and if so, how would you handle datetimes coming from different timezones and displaying them to people in other timezones ?
Of course I could customize the formatRelative helper to play with getTimezoneOffset and get the wanted result, but I wanted to know if there is something better to do.
Thanks a lot ahead !
The key to understanding your question is what you wrote in the comments:
Getting the Json, containing datetimes in the format 2016-02-28 10:15:53 - that's UTC time
You should ensure the value in JSON is in full ISO8601 format, including the appropriate offset or Z character to indicate UTC: 2016-02-28T10:15:53Z
Without the offset, most implementations will consider the value to be represented in local time, which explains your results.
Thus, the problem is with your server-side code, not your JavaScript code. There may be a client-side workaround you could apply when the date string is parsed from JSON, but really the best solution would be to qualify it at the server.
I've got a problem with timestamps between java and javascript.
I already found these 2 questions about the timestamps and I know about the timechanges all over the years.
Timestamp deviation Java vs Javascript for old dates (3600secs)
Why is subtracting these two times (in 1927) giving a strange result?
Basically at midnight at the end of 1927, the clocks went back 5
minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened
twice, and it looks like Java is parsing it as the later possible
instant for that local date/time.
What the problems makes is that when I have javascript and put the timestamp in there then I get an other date than the Java date. I need this to show the correct date on the webpage. I know I can request the date as a string but I prefer using a timestamp.
Java date 0001-01-01 timestamp is -62135773200000
JavaScript date 0001-01-01 timestamp is -62135596800000
The difference is -176400000; 49 hours.
Does anybody know what I can do for this.
Personally, I would avoid passing numerical timestamps around from a system in one language to a system in another language for the sole reason that the languages may differ in the algorithm they use to generate them.
There is an international standard in place (ISO-8601) to deal with passing timestamps from system to system. In this your date representation becomes 0001-01-01T00:00:00+00:00. I would recommend using this approach, as it's a widely accepted solution for this very problem.
This might be related to TZ and DST settings which diverge from browser to java. In order to nail it down, I recommend to use ISO-8601 formats like 2008-02-01T09:00:22+05, this is ambiguous-less
I pick some date and time in javascript and then want to store it on server (.NET). Dates are supposed to be in future from the current moment (so they won't be before 1970).
Having read topics here on SO I learnt it's better to store date as a string and people suggest using Date.prototype.toISOString() or Date.prototype.toUTCString().
I've read that toISOString() is not available in IE 7. And I'd like to know other differences, when I should choose one or another function.
They're for different purposes.
UTC is the primary time standard by which the world regulates clocks and time.
ISO is standard format time. ISO also supports ms in its format.
So if you want to send data to the server, send the ISO, because ISO is the standard format:
var date = new Date();
sendDate(date.toISOString());
You can also use toISOString in IE7 polyfill.
I hope it will helpful to you.
Summary About toISOString() :-
The toISOString() method returns a string in ISO format (ISO 8601 Extended Format), which can be described as follows: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always UTC as denoted by the suffix "Z".
Refer Below link for more information about toISOString().
Date.prototype.toISOString()
Summary About toUTCString() :-
The toUTCString() method converts a date to a string, using the UTC time zone.
Refer Below link for more information about toUTCString()
Date.prototype.toUTCString()
Always use .toISOString()
They give almost the same information, but in different formats. Here is what I get on my machine.
new Date().toISOString()
"2019-10-11T18:56:08.984Z"
new Date().toUTCString()
"Fri, 11 Oct 2019 18:56:08 GMT"
There are 4 reasons .toISOString() is more often what you want than .toUTCString().
A. More convenient sorting
When you sort alphabetically, the "2019-10-11T18:56:08.984Z" pattern of .toISOString() gives you the correct date order.
B. Millisecond precision
.toISOString() provides millisecond values, whereas .toUTCString() does not.
C. Any user can interpret correctly
The .toUTCString() value may be more familiar to human end-users, but only if the language settings are suitable for them. In contrast, the .toISOString() is the same regardless of language settings.
D. Reproducibly regeneratable by software
You can easily convert the ISO date string to a Javascript Date object, and then back again, regenerating exactly the same string. This is regardless of who gave you the ISO date string, where the server is, and where you are.
This is not automatically true for the UTC string. For example, if a second instance of your app system is running in a different time zone, or language, it's .toUTCstring() may use different numbers or words (respectively) to represent the same instant in time. It will be difficult for it to create a UTCString that matches what was made by the first instance of the app, since in general it will not know the language or timezone in which the first UTC string was produced.
I think nobody needs .toUTCString()
I don't know why `.toUTCString()` exists. Its word-heavy format makes it useless for internal storage of dates in your program, because it varies depending on your language and timezone setting etc.
So maybe it is to produce something nice to display externally for the user to see? Well, not really. Anyone who is not in the London time zone will not find it very helpful.
I live in London. And even I, even if I was writing an app purely for use by me, solely on my system, and only in my home, would still not want to use .toUTCString(). Because it is showing UTC (also known as GMT). London is not always on GMT. In summer, we move to GMT+1, so the .toUTCString() result would mislead anyone who didn't notice the "GMT" and do the time adjustment in their head.
If I wanted a natural-language time, to make non-computer literate users comfortable, I would construct it manually from parts, using a library like moment.js. If I wanted a quick-and-dirty solution, I would use .toString() which at least will move to Summer time when appropriate.
I have a jQuery app that sends a date object to python for parsing. The problem is that when I try to use my jQuery on the Windows machine, the date object looks like this:
Tue Mar 12 2013 00:00:00 GMT-0600(Mountain Daylight Time)
Whereas on my Mac, I get:
Tue Mar 12 2013 00:00:00 GMT-0600(PST)
When I try to parse these in Python with the strptime function, it fails because it doesn't understand the time zones on the end of the first (the MDT one). It complains that is an "unknown string format".
How do I resolve this? Am I doing something wrong?
The best solution here is probably to have your jQuery code convert its datetimes to GMT before sending them. (If you want the timezone as well, send it separately.) Then you can get them out of the JSON (or whatever) on the Python side, turn them into GMT datetime objects with strptime, and use them, and you're done.
But the simplest solution,* with the least code change, is to just let jQuery do the wrong thing and throw away the timezone on the Python side. Basically, instead of this:
dt = datetime.datetime.strptime(jsondate)
do this:
dt = datetime.datetime.strptime(jsondate.partition('(')[0])
Notice that throwing away everything after the '(' still leaves you with the -0600 part; you're just losing the "PST" or "Mountain Daylight Time" part.
And those parts were not doing you any good anyway. datetime doesn't understand these timezone names. And, even if it did, it has nothing to map them to except for offsets (which you already have). If you want real timezones, you need some third-party library like pytz.**
On top of that, strptime specifically returns naive datetime objects, not aware ones. So, even if datetime could parse and look up the timezones, it still wouldn't do anything useful with them, unless you parsed the datetime, then pulled out the timezone and parsed it separately and looked it up and then called astimezon on the datetime.
So, in summary, the worst-case scenario for throwing this information away is exactly what you already have.
As a side note, on three projects in a row, I pushed a datetime serializer into my JSON en/decoder on the Python side (and a matching serializer on the JS side, for the one that had a JS side) specifically so I could pass a UTC datetime (in ISO8601 format, because that's as easy to use for computers as a seconds-since-epoch, and a lot easier to read/edit for humans) and a timezone offset today, but switch to a tzinfo key if it because important later. All three times, it never became important… And the projects where it has been important, I've usually been passing around ICAL schedules or pre-Gregorian dates or other similarly fun stuff.
Finally, as someone who's written way too much date-related code over my career, I have to say this: If you know of any evil overlords planning to take over the world, if they promise to abolish timezones, I am willing to overlook their other programs of enslaving humanity or making kittens fight babies and sign up as a henchman.
* … at least simplest for me, since I know Python a lot better than JS and jQuery. :)
** IIRC, pytz can't handle NT-style timezone keys like "Mountain Daylight Time" either, so you actually need yet another library to handle that. I think I got that out of a library that did all kinds of MS datetime stuff, including handling the differences between Microsoft's three similar 1601-ish epoch times (two not-quite-the-same epochs, different rules for special "end of time" and "start of time" and "not a date" values, …).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a standard date/time format that can be passed on a URL?
What is a good way for a RESTful resource to accept a datetime object? Specifically, I'm not sure what is a good way to represent the date and time as a query argument in the URL.
I was thinking of doing something like this:
GET /Calls?start=YYYY-MM-DD_HH:MM:SS
I'm using Javascript/jQuery on the Client and Python on the back end, so ideally it would be a format that could easily be written in Javascript and read in Python.
Thanks!
Use the ISO 8601 standard to encode the time argument as a string. It's readable for humans and supported by tons of libraries across many languages.
I'd recommend against using Unix time. Your sysadmins will thank you when they're asked to crawl or parse your web server logs for API calls. Using ISO 8601 will avoid them having to build a secondary step into that process to convert the Unix time number into something that actual humans have to understand.
Most datetime libraries (definitely both Python and JS) follow the same formatting approach, namely format strings. I'd go with any one that just uses digits, and uses descending order of size, i.e. YYYYMMDDhhmmss.
The one other thing to consider before jumping into a format is whether you might need to parameterize by something more akin to a date range, and if including the seconds, minutes, hours, etc. might over-specify the request and make it hard for the client to locate the data they are looking for.
unix time... http://en.wikipedia.org/wiki/Unix_time
why not just YYYYMMDDHHMMSS ?
As long as both sides can follow this format, I don't see any problem