22
var exampleDate='23-12-2010 23:12:00';  

I want to convert above string into a date and have tried a couple things:

var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN

This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?

serraosays
  • 7,163
  • 3
  • 35
  • 60
Chitresh
  • 3,022
  • 12
  • 35
  • 40

7 Answers7

27

The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:

The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

This format includes date-only forms:

YYYY

YYYY-MM

YYYY-MM-DD

It also includes time-only forms with an optional time zone offset appended:

THH:mm

THH:mm:ss

THH:mm:ss.sss

Also included are “date-times” which may be any combination of the above.

If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • At the time this answer was written, parsing of date strings was implementation dependent, therefore there were **no** strings that are "guaranteed to work". Since then, ISO 8601 long format strings with no time zone were required to be parsed as UTC by browsers consistent with ES5 (such as Firefox) and local by browsers consistent with ECMA 2015 (such as Chrome and Safari). All 3 behaviours can be seen in browsers in current use (2015) such as IE8 returning NaN, Firefox 40 treating it as UTC and Chrome 44 as local. So there are still **no** strings that are "guaranteed to work". – RobG Aug 22 '15 at 05:20
6

Above format is only supported in IE and Chrome.

so try with another formats. following are some formats and there supporting browsers.

<script type="text/javascript">

//var dateString = "03/20/2008";  // mm/dd/yyyy [IE, FF]

 var dateString = "2008/03/20";  // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008";  // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008";  // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008";  // mmm dd, yyyy [IE, FF]

// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate); 
</script>
Community
  • 1
  • 1
Romani
  • 3,241
  • 4
  • 25
  • 28
4

You could parse it manually with a regular expression then call the date constructor with the date elements, as such:

var parseDate = function(s) {
  var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
  var m = re.exec(s);
  return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800
maerics
  • 151,642
  • 46
  • 269
  • 291
2

JavaScript should support conversion at least from the following dateStrings:

* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy

Try with:

  var exampleDate='12/23/2010 23:12:00';
  var date = new Date(exampleDate); 
hade
  • 1,715
  • 1
  • 16
  • 24
1

Use datejs and this code:

var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');

myDate should be a correctly constructed Date object.

darioo
  • 46,442
  • 10
  • 75
  • 103
1

@casablanca has a good answer but it's been 10+ years and this still has a lot of weight in Google so I thought I'd update with a new answer.

TL;DR

// Use an ISO or Unix time string to generate `Month DD, YYYY` 
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${newDate.getDate()}, ${newDate.getFullYear()}`
// yields: December, 23 2010 (if you want date suffix, read until the end)

Background: Dates come in a lot of formats, but you're mostly going to receive:

  • An ISO 8601 format date (YYYY-MM-DDTHH:mm:ss.sssZ) where Z is a UTC timezone offset. You might also get a subset of this (ie, YYYY-MM-DD)
  • Unix timestamp format date (1539734400), where the number is literally the total amount of milliseconds since the beginning of Unix time, Jan 1st 1970.

Basics: JS has a built-in Date prototype that accepts ISO 8601 and derivatives (of just time or just date). You can instantiate with new Date and return a date object OR you can use the Date.parse() method to return a Unix timestamp.

const dateObj = new Date('23-12-2010:23:12:00') // returns date object
const dateDateOnly = new Date('23-12-2010') // returns date object
const dateTimeOnly = new Date('23:12:00') // returns date object
const dateString = Date.parse('23-12-2010:23:12:00') // returns Unix timestamp string

You can also break the date into 7 parameters: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds with the time zone offset - NOTE, I've used the multi-params approach only once in my career. Since I'm in Texas I get, UTC-5 (Central Time) when I run the following:

const dateByParam = new Date(2021, 2, 26, 13, 50, 13, 30) // Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time)

New-ish Stuff toLocaleString: Typically, the return from the Date object is still pretty dense like our last example (Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time) so additional methods have been added to help developers.

Typically with a date, I want something like March 21st, 2021 - the day and year have been easy to get for a long time:

// Assuming myDate is a JS Date object...
myDate.getDate() // date on the calendar, ie 22
myDate.getDay() // day of the week, where 0 means Sunday, 1 means monday, etc
myDate.getFullYear() // 4 digit year, ie, 2021

But I've always had to build a function to turn getDay into January, February, March, not anymore. toLocaleString() gives you some new superpowers. You can pass it two params, a string for region (ie, en-us) and an object with what you want back (ie, { month: 'long' }). This helps internationalize the response, if need be.

// Again, assuming myDate is a JS Date object...
myDate.toLocaleString('en-us', { month: 'long' } ) // March

Date Suffix I've still seen no built-in way to get the suffix for a date, like th, st, so I built this utility function that uses the modulus % operator to check the divisor of each day number and apply the right suffix (aimed at an American audience but might be the same elsewhere?).

/**
 * setDateSuffix()
 * 
 * Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
 * 
 * @param { integer } num - a number date
 */

export const setDateSuffix = (num) => {
  const j = num % 10,
        k = num % 100

  if (j === 1 && k !== 11) {
    return num + "st";
  }
  if (j === 2 && k !== 12) {
    return num + "nd";
  }
  if (j === 3 && k !== 13) {
    return num + "rd";
  }

  return num + "th";
}

Altogether now.. Long winded way of getting here, but if I am given an ISO or Unix date and I want Month DDth, YYYY, this is what I run:

// setDateSuffix IS NOT PART OF BUILT-IN JS!
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${setDateSuffix(newDate.getDate())}, ${newDate.getFullYear()}`
// yields: December 23rd, 2010 

Note - all of this will likely change, hopefully for the better, when temporal becomes a reality in JS: https://github.com/tc39/proposal-temporal. Look forward to somebody's 2030 update of this post!

serraosays
  • 7,163
  • 3
  • 35
  • 60
0

Just use in this format:

var exampleDate='2010-12-23 23:12:00'; 
Pearl
  • 8,373
  • 8
  • 40
  • 59