Converting json results to a date [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to format a JSON date?
I have the following result from a $getJSON call from JavaScript. How do I convert the start property to a proper date in JavaScript?
[
{"id":1,"start":"/Date(1238540400000)/"},
{"id":2,"start":"/Date(1238626800000)/"}
]
Thanks!

You need to extract the number from the string, and pass it into the Date constructor:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

I use this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Update 2018:
This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.
2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object
using dateObject.toISOString()
1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object
using dateObject.getTime()

If you use jQuery
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code.
http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);

Related

Database timestamps returning intriguing values

I am using javascript to read the values of a JSON object that is returned after a GET call.
The database that provides the values is making a timestamp like this:
26-04-2019 17:22:25;
into:
1556233200000....
How can I fix this? I have no access to the database.
This is no intriguing value. It is in epoch time.
You can simply convert it back to an ISO string by using declaring JavaScript's Date instance.
const dateValue = new Date(1556233200000);
console.log(dateValue);
That number (1556233200000) is the number of milliseconds since January 1, 1970 (1/1/1970).
More information about JavaScript date is available here: Date - JavaScript MDN.

How to work with datetimes betwixt javascript, JSON, and python, and mongodb?

Colleague and I have scabbed together a little app that uses a bunch of JS in the browser, and communicates with a Tornado (Python3) server via JSON, the server uses mongodb as a backing store for persistent data. This is a sort of first for both of us.
What we're finding difficult is how to interchange datetime information between the JS and Python. We do believe that we should use UTC times for everything. JSON doesn't have a datetime literal, so we have to encode it somehow. We naively (?) used the JS notion of milliseconds from 1970 and have been sharing big integers back and forth. So the JS code might get the current utc now time with something like:
var newTime = new Date().getTime();
On the Python3/mongo side, we'd like to use real datetime objects, so we convert that with something like:
datetime.datetime.utcfromtimestamp(jsMilliseconds / 1000)
But then when we have to send date back, said Python3 object only has a timestamp() method. And round tripping that doesn't seem to create the same time. So we've been frustrated with this.
What we're looking for is for someone with experience to give us a good set of idioms to use here. Should we be using strings, instead of the ms integers when passing back and forth with JSON? What are the recommended methods to use on both sides to go between that format? Or should we stick with the integers and which methods should we be using then?
There are obviously a lot of requirements to consider when dealing with time. However, in the case you want to maintain a Date/Time to be displayed to user in their time zone and use mongo/python/java/javascript, I've used ISO 8601 date formats and always store UTC (Zulu) time. Also, if you truly want to maintain the actual time that something occured, not only do you need to store the "date/time" you need to also store the "timezone" (for example IANA timezone string) where the event occurred.
For a lifetime a reading, you can search for "date time best practices". This answer has a good start on discussion: Daylight saving time and time zone best practices
Alright, now to the code (all of this can be found readily on the internet if you search for
" parse||output ISO 8601 parsing" (e.g. "python parse ISO 8601 date string"):
JSON - on the wire between JavaScript and Python backend send a complex (can be simple if you have no need to preserve time zone) object with ISO-8601 formatted string and string to store time zone string:
{
"dateTime": "1970-07-10T12:00:00.047Z",
"timeZone": "America/New_York"
}
Java Script
a. read datetime string JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse
var d = Date.parse("2011-04-26T13:16:50Z");
b. write datetime string How do I output an ISO 8601 formatted string in JavaScript?
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
Python
a. read datetime string How do I translate a ISO 8601 datetime string into a Python datetime object?
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
b. write datetime string Python - Convert date to ISO 8601
import dateutil.parser as parser
date.isoformat()
Mongo - store datetime as native datetime field http://docs.mongodb.org/manual/reference/mongodb-extended-json/#date
a. store datetime string (notice "$date" and that datetime is in ZULU/UTC (denoted by 'Z')):
"dateTime" : { "$date" : "1970-07-10T13:00:00.047Z"}
Reference:
1. IANA TimeZone Databasehttp://en.wikipedia.org/wiki/Tz_database
2. The google calendar API (event resource) can be used as an example for RFC 3339, as well (see start/end): https://developers.google.com/google-apps/calendar/v3/reference/events

Passing datetime with http request

I need to pass a date time (in 2012-09-23 21:00:00 format generated by dropdown boxes and converted to that format with javascript (client side that is)) with GET method to a php file which then gets mysql records sorted by that time.
What is the best way of passing this date?
The options I consider are:
making separate get parameters for each piece of info (e.g ?startYear=2012&startMonth=09&startDay=23&startHour=....)
this could work, but what if I add more different filters. It will be too busy there. Or it's not an issue?
Passing timestamp. I consider this to be the best option. However when I convert the date to timestamp it gives me incorrect result. The function will be below.
Passing in 2012-09-23 21:00:00 format by pre-processing with encodeURIComponent
Any suggestions?
Date to timestamp conversion (related to point 2):
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}

JavaScript date() Object returns NaN with getYear (and other)

I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));

Proper way to format date from database using javascript/jquery

I am calling my database which contains a datetime datatype. The date looks like this:
2005-05-23 16:06:00.000
I would like to display this in a table when a user selects a certain item from a list. I call my controller action and return Json of all the times and put them in a table. The problem is the date is completely wrong. What is displayed is this:
/Date(1255470180000)/
The date that is returned isn't even parsable (which I don't want to do anyway) so I can't even get the data if I wanted to. Any ideas?
The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). If you isolate the numeric portion, convert it into a number, and feed it into the Date constructor you'll get an actual date to work with, which you can then format as you like.
var ticks, dt;
// Isolate the numeric portion of the value
ticks = /[0-9]+/.exec(json.dateValue)[0];
// Convert to a number
ticks = parseInt(ticks);
// Convert to a date
dt = new Date(ticks);
Alternately, if the JSON serializer on the server supports a "replacer" parameter as Crockford's and ECMAScript 5th edition's do, you could supply a replacer that formatted the date into a string server-side and handle it there, since you said you don't want to parse the date client-side (although the jQuery tag suggested to me maybe you did).
The other alternative is to return the formatted string from the controller action. You could even leave the timestamp and return a second field as "Formatted Timestamp" or something similar.
var listFromDb = ...
return new Json(listFromDb.Select(itemFromDb => new List { new
{ Date = itemFromDb.Date, FormattedDate = FormatDate(itemFromDb.Date), ...}
I ended up formatting the code in the controller action instead.
I just cast the datetime property to a string using .ToString() and got the desired results.
Thanks for the help though guys.

Categories