Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript datetime to string and back to datetime?

if you had to store the current javascript datetime in a string what would it look like and could you convert it back to a datetime for javascript to read?

What I am trying is not working given the current xml string of Tue Dec 23 12:02:08 EST 2014

var xmlImagePath = $(this).find('pathName').text();

var xmlStartTime = $(this).find('startTime').text();
xmlStartTime = new Date(xmlStartTime);

var fortnightAway = new Date(xmlStartTime);
var numberOfDaysToAdd = 14;
fortnightAway.setDate(fortnightAway.getDate() + numberOfDaysToAdd);


if (fortnightAway < xmlStartTime) {
    alert("here");
}

I do not believe xmlStartTime = new Date(xmlStartTime); is setting the xmlStartTime to a datetime object..

Also, What is the correct format to store the datetime into the xml so that it is easier to test later?

like image 855
JoJo Avatar asked Dec 22 '14 18:12

JoJo


2 Answers

One easy way to serialize dates is to use JSON.stringify and JSON.parse:

var serialized = JSON.stringify(new Date());

var deserialized = new Date(JSON.parse(serialized));

If you don't have the JSON object available, you can do this, which is essentially the same, but with less nested code:

var iso = (new Date()).toISOString();

var dateObj = new Date(iso);

And if you don't have .toISOString (IE 8 or earlier), there is a polyfill here.

like image 88
JLRishe Avatar answered Sep 17 '22 15:09

JLRishe


Have a look at moment.js library. If you are able to use an external library, this one will save you many headaches dealing with times in javascript. I have a fiddle that demonstrates many possibilities, and I added your example to the end of the list in this fiddle:

http://jsfiddle.net/JamesWClark/9PAFg/

For example, moment('Tue Dec 23 12:02:08 EST 2014').format() will output 2014-12-23T11:02:08-06:00 from which you should easily be able to create a DateTime object.

Using an example from your code, you might try this:

var xmlStartTime = moment($(this).find('startTime').text());
xmlStartTime = new Date(xmlStartTime);
like image 41
ThisClark Avatar answered Sep 20 '22 15:09

ThisClark