The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method - use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

Answer from Pavel Hodek on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_dates.asp
JavaScript Dates
JavaScript will (by default) output dates using the toString() method. This is a string representation of the date, including the time zone.
🌐
W3Schools
w3schools.com › jsref › jsref_tostring_date.asp
JavaScript Date toString() Method
The toString() method returns a date object as a string. Every JavaScript object has a toString() method. The toString() method is used by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be ...
🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
Independent of input format, JavaScript will (by default) output dates in full text string format:
🌐
W3Schools
w3schools.com › jsref › jsref_parse.asp
JavaScript Date parse() Method
❮ Previous JavaScript Date Reference Next ❯ · let ms = Date.parse("March 21, 2012"); Try it Yourself » · parse() parses a date string and returns the time difference since January 1, 1970. parse() returns the time difference in milliseconds.
Top answer
1 of 16
1087

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method - use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

2 of 16
452

Unfortunately I found out that

var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());

returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.

The bulletproof solution is the following:

var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

🌐
W3Schools
w3schools.com › jsref › jsref_todatestring.asp
JavaScript Date toDateString()
The toDateString() method returns the date (not the time) of a date object as a string. toDateString() is an ECMAScript1 (JavaScript 1997) feature. ... If you want to use W3Schools services as an educational institution, team or enterprise, ...
🌐
W3Schools Blog
w3schools.blog › home › javascript date tutorial
JavaScript Date Tutorial - W3schools
April 21, 2019 - toString() method: Use: To get the date in the form of a string.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
Furthermore, implementations are allowed to support other date formats when the input fails to match this format. The toISOString() method returns a string representation of the date in the date time string format, with the time zone offset always set to Z (UTC).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › parse
Date.parse() - JavaScript | MDN
// Standard date-time string format const unixTimeZero = Date.parse("1970-01-01T00:00:00Z"); // Non-standard format resembling toUTCString() const javaScriptRelease = Date.parse("04 Dec 1995 00:12:00 GMT"); console.log(unixTimeZero); // Expected output: 0 console.log(javaScriptRelease); // Expected output: 818035920000
🌐
W3Schools
w3schools.com › jsref › jsref_obj_date.asp
JavaScript Date Reference
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
🌐
W3Schools
w3schools.com › jsref › jsref_tolocaledatestring.asp
JavaScript Date toLocaleDateString() Method
The toLocaleDateString() method returns the date (not the time) of a date object as a string, using locale conventions. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › toString
Date.prototype.toString() - JavaScript | MDN
const event = new Date("August 19, 1975 23:15:30"); console.log(event.toString()); // Expected output: "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" // Note: your timezone may vary ... A string representing the given date (see description for the format).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › Date
Date() constructor - JavaScript | MDN
The returned date's timestamp is the same as the number returned by Date.now(). ... An integer value representing the timestamp (the number of milliseconds since midnight at the beginning of January 1, 1970, UTC — a.k.a. the epoch). ... A string value representing a date, parsed and interpreted using the same algorithm implemented by Date.parse().
🌐
Index.dev
index.dev › blog › convert-string-to-date-javascript
6 Easy Ways To Convert String to Date in JavaScript
Learn six practical ways to convert strings to dates in JavaScript. Explore techniques like Date Constructor, Moment.js, Regular Expressions, and more, with code examples to improve your date manipulation tasks.
🌐
Turing
turing.com › kb › converting-string-to-date-in-js
Learn the Basics of Converting String to Date in JavaScript
The given example demonstrates how to use the constructor of the Date class to convert a date from a string to a Date object when the input does not adhere to the ISO standard. There are multiple ways to convert a string value to date in JavaScript using third-party libraries like Moment.js, Date-fns, Day.js, and Temporal.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › toDateString
Date.prototype.toDateString() - JavaScript | MDN
const event = new Date(1993, 6, 28, 14, 39, 7); console.log(event.toString()); // Expected output: "Wed Jul 28 1993 14:39:07 GMT+0200 (CEST)" // Note: your timezone may vary console.log(event.toDateString()); // Expected output: "Wed Jul 28 1993" ... A string representing the date portion of ...
Top answer
1 of 16
3084

If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

Options key examples:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute: The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".
  8. hour12:
    The representation of time format.
    Accepts boolean true or false

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.

For different languages:

  1. "en-US": For American English
  2. "en-GB": For British English
  3. "hi-IN": For Hindi
  4. "ja-JP": For Japanese

You can use more language options.

For example

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.

// Example
9/17/2016, 1:21:34 PM

References:

  • toLocaleString()

  • toLocaleDateString()

2 of 16
1756

For custom-delimited date formats, you have to pull out the date (or time) components from a DateTimeFormat object (which is part of the ECMAScript Internationalization API), and then manually create a string with the delimiters you want.

To do this, you can use DateTimeFormat#formatToParts. You could destructure the array, but that is not ideal, as the array output depends on the locale:

{ // example 1
   let formatter = new Intl.DateTimeFormat('en');
   let example = formatter.formatToParts();
   console.log(example);
}
{ // example 2
   let formatter = new Intl.DateTimeFormat('hi');
   let example = formatter.formatToParts();
   console.log(example);
}

Better would be to map a format array to resultant strings:

function join(date, options, separator) {
   function format(option) {
      let formatter = new Intl.DateTimeFormat('en', option);
      return formatter.format(date);
   }
   return options.map(format).join(separator);
}

let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date, options, '-');
console.log(joined);

You can also pull out the parts of a DateTimeFormat one-by-one using DateTimeFormat#format, but note that when using this method, as of March 2020, there is a bug in the ECMAScript implementation when it comes to leading zeros on minutes and seconds (this bug is circumvented by the approach above).

let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${day}-${month}-${year}`);

When working with dates and times, it is usually worth using a library (eg. luxon, date-fns, moment.js is not recommended for new projects) because of the many hidden complexities of the field.

Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).