How to Create a Date Object from String in JavaScript

How to create a date object from string in javascript

var d = new Date(2011,10,30);

as months are indexed from 0 in js.

Parsing a string to a date in JavaScript

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.

Get String in YYYYMMDD format from JS date object?

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();

return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};

var date = new Date();
date.yyyymmdd();

Creating a date object from a date string and locale

Looking at the question's comments, I believe sometimes people just don't understand the question and start blaming the problem itself. It's ridiculous :D

This may not be the perfect way to go about it (there can be something cleaner and shorter), but this definitely works.

locale = 'en-GB';
value = '07/06/2021';

moment.locale(locale);
const localeData = moment.localeData();
const format = localeData.longDateFormat('L');
console.log(moment(value, format).format('YYYY-MM-DD')); // '2021-06-07'

How to create a date object from string consisting of Hour, Minute, Date, Month and Year?

Seems to work fine here:

'use strict';
let o = new Date('6 Aug 2020 23:40');
console.log(o);

How to create a date object from a date-string which contains AM/PM?

This works:

new Date( '1 Jan 1900 8:20:00 PM' )

and is equivalent to

new Date( '1 Jan 1900 20:20:00' )

Live demo: http://jsfiddle.net/cVE2E/

Transform string date to Date object in JS

You can consider doing it like this:

const str = "2022-06-29T15:30:00+00:00";

const date = new Date(str);

console.log(date); // ️ Wed Jun 29 2022 22:30:00

As for sorting array based on dates, you can take a look at How to sort an object array by date property.

Create JavaScript Date object from date string + time string + timezone offset string

I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00)

Date objects are extremely simple, they're just a time value that is an offset in milliseconds since 1970-01-01T00:00:00Z, so are inherently UTC. The built–in parser is unreliable and lacks any functionality such as format tokens.

So if you have separate values like:

  • Date string (2020-05-05)
  • Time string (15:30)
  • Timezone offset (-09:00)

then you can create a string that is compliant with the format defined in ECMA-262 and that should be parsed correctly by the built–in parser, e.g.

new Date('2020-05-05T15:30:00.000-09:00')

However, general advice is to avoid the built–in parser due to differences in implementations. Also, the format must be exact (e.g. including seconds and milliseconds in the timestamp, colon (:) in the offset) or some implementations will reject it as malformed and return an invalid date.

Once you have a Date object, getting a "local" timestamp with offset is an issue of formatting, which has been answered many times before (e.g. How to format a JavaScript date). There aren't any decent built–in formatting functions (toLocaleString with options is OK for some purposes but generally lacking in functionality), so you'll have to either write your own function, or use a library.

The following examples use Luxon, which is suggested as the upgrade path from moment.js.

With Luxon, if you specify a representative location, you'll get the offset for that location at the date's date and time. Alternatively, you can fix the offset to a set value, essentially setting it for a timezone without a representative location, so it doesn't have any reference to daylight saving or historic offset changes:

let DateTime = luxon.DateTime;
// Offset per the specified locationlet d0 = DateTime.fromISO('2020-01-01', {zone: 'America/Yakutat'});let d1 = DateTime.fromISO('2020-06-30', {zone: 'America/Yakutat'});console.log(d0.toString());console.log(d1.toString());
// Fixed offset per the supplied stringlet d2 = DateTime.fromISO('2020-05-05T15:30:00.000-09:00', { setZone: true});let d3 = DateTime.fromISO('2020-01-01T15:30:00.000-09:00', { setZone: true});console.log(d2.toString());console.log(d3.toString());
<script src="https://cdn.jsdelivr.net/npm/luxon@1.24.1/build/global/luxon.min.js"></script>


Related Topics



Leave a reply



Submit