Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date.parse() and null dates

I'm trying to sort a list of dates, but I'm struggling with null dates which aren't being handled consistently.

So I need something like:

var date = Date.parse(dateString);
if (!date) {
    date = Date.MinValue;
}

but I'm struggling to find the correct syntax. Thanks


Update: The bug turned out to be a different problem. I have Datejs imported for use in another part of the project, so I hadn't realised that Datejs defines a Date.parse() method which was overriding the standard JavaScript method.

Anyway, it turns out that Datejs has a weird bug which means it doesn't handle dates beginning with "A" properly. So actually my null dates were being ordered correctly, it was just April and August dates were then being mixed up with them.

The fix is to use the Datejs Date.parseExact method which lets you provide a specific format string, see here.

like image 201
fearofawhackplanet Avatar asked Jul 16 '10 10:07

fearofawhackplanet


People also ask

How check date is null in JavaScript?

Use the value property to check if an input type="date" is empty, e.g. if (! dateInput. value) {} . The value property stores the date formatted as YYYY-MM-DD or has an empty value if the user hasn't selected a date.

What can I use instead of date parse?

You can use the DATE function instead of the DATEPARSE function if the data you're working with doesn't have the DATEPARSE function or if the field you're trying to convert has a numeric data type.

What is date parse in JavaScript?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.

What does new date () return?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.


1 Answers

parse() returns NaN on an impossible parse so how about just;

 var date = Date.parse(dateString) || 0;
like image 58
Alex K. Avatar answered Sep 21 '22 19:09

Alex K.