Search code examples
javascriptstringdatetitaniumappcelerator

Javascript comparing two dates returns NaN


I'm building something in javascript with Titanium Appcelerator that compares two dates.

I store expiration as a property string. The value is 2012-02-29 05:00:00 +0000 The value of current_date is 2012-03-05 22:49:54 +0000

However, when I do Date.parse on expiration its result is NaN, as compared to current_date which returns the unix timestamp 1330987794000.

Any ideas why?

var current_date = new Date();
var expiration = Ti.App.Properties.getString("expiration");
Ti.API.info(expiration); // returns 2012-02-29 05:00:00 +0000
Ti.API.info(current_date); // returns 2012-03-05 22:49:54 +0000

var check_expiration = Date.parse(expiration);
var check_current_date = Date.parse(current_date);
Ti.API.info(check_expiration); // returns NaN
Ti.API.info(check_current_date); // returns 1330987794000

Solution

  • Date.parse() does not return a Date instance. Instead, it returns an integer representing the number of milliseconds since epoch. Or if whatever it was passed wasn't parseable, it will return NaN.

    In your code, current_date is an instance of Date. A date object is parseable as a date, obviously. When you log it out, it's calling toString() on that date object to figure out how to log it.

    But expiration is not a Date, it's a string. And the JS env of the platform you are running on does not recognize that string format as a parseable Date string.

    I would suggest storing dates as integers instead. dateObj.getTime() or Date.now() will both return integers that you can save, and then turning them back into a real date object as as simple as:

    myDate = new Date(parseInt(dateIntegerAsString, 10));
    

    Which will work reliably cross platform, and it probably much faster than the more robust date parsing you are going for here.