Skip to content
Fix Code Error

Converting a string to a date in JavaScript

March 13, 2021 by Code Error
Posted By: Anonymous

How can I convert a string to a date in JavaScript?

var st = "date in some format"
var dt = new date();

var dt_st= //st in date format same as dt

Solution

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.

Answered By: Anonymous

Related Articles

  • Integrating CKEditor with Aurelia
  • Convert Java Date to UTC String
  • Attempt to use Aurelia plugin causing 404 error in browser
  • Using aurelia-cli unable to get bootstrap and a couple of…
  • Generating a drop down list of timezones with PHP
  • Avoid creating new session on each axios request laravel
  • What's the difference between Instant and LocalDateTime?
  • Creating an appoint record for health professionals
  • Failed to authenticate on SMTP server error using gmail
  • Should MySQL have its timezone set to UTC?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Next Post:

How can I symlink a file in Linux?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error