Javascript date parsing from string

Date.parse()

The Date.parse() static method parses a string representation of a date, and returns the date’s timestamp.

Only the date time string format is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.

Try it

Syntax

Parameters

A string in the date time string format. See the linked reference for caveats on using different formats.

Return value

A number representing the timestamp of the given date. If dateString fails to be parsed as a valid date, NaN is returned.

Description

This function is useful for setting date values based on string values, for example in conjunction with the setTime() method.

Because parse() is a static method of Date , you always use it as Date.parse() , rather than as a method of a Date object you created.

Examples

Using Date.parse()

The following calls all return 1546300800000 . The first will imply UTC time because it’s date-only, and the others explicitly specify the UTC timezone.

.parse("2019-01-01"); Date.parse("2019-01-01T00:00:00.000Z"); Date.parse("2019-01-01T00:00:00.000+00:00"); 

The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system, because it has both date and time.

Читайте также:  Зависает при запуске css

Non-standard date strings

Note: This section contains implementation-specific behavior that can be inconsistent across implementations.

Implementations usually default to the local time zone when the date string is non-standard. For consistency, we will assume that the code uses the UTC timezone.

.parse("Jan 1, 1970"); // 0 in all implementations Date.parse("Thu, 01 Jan 1970 00:00:00"); // 0 in all implementations Date.parse("1970,1,1"); // 0 in Chrome and Firefox, NaN in Safari Date.parse("02 01 1970"); // 2678400000 in Chrome and Firefox (Sun Feb 01 1970 00:00:00 GMT+0000); // NaN in Safari // With explicit timezone Date.parse("Thu, 01 Jan 1970 00:00:00 GMT+0300"); // -10800000 in all implementations in all timezones // Single number Date.parse("0"); // 946684800000 in Chrome (Sat Jan 01 2000 00:00:00 GMT+0000); // NaN in Firefox; // -62167219200000 in Safari (Sat Jan 01 0000 00:00:00 GMT+0000) // Two-digit number that may be a month Date.parse("28"); // NaN in all implementations // Two-digit year Date.parse("70/01/01"); // 0 in all implementations // Out-of-bounds date components Date.parse("2014-25-23"); // NaN in all implementations Date.parse("Mar 32, 2014"); // NaN in all implementations Date.parse("2014/25/23"); // NaN in all implementations Date.parse("2014-02-30"); // NaN in Safari and Firefox; // 1393718400000 in Chrome (Sun Mar 02 2014 00:00:00 GMT+0000) Date.parse("02/30/2014"); // 1393718400000 in all implementations 

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

Javascript date parsing from string

Last updated: Jan 13, 2023
Reading time · 4 min

banner

# Convert a String to a Date object in JavaScript

Use the Date() constructor to convert a string to a Date object.

The Date() constructor takes a valid date string as a parameter and returns a Date object.

Copied!
const str = '2022-09-24'; const date = new Date(str); console.log(date); // 👉️ 2022-09-24T00:00:00.000Z console.log(date.toDateString()); // 👉️ Sat Sep 24 2022

convert string to date object

We used the Date() constructor to convert a string to a Date object.

# Dealing with Invalid Dates

If you get an invalid Date when creating the Date object, you need to format the string correctly before passing it to the Date() constructor.

Copied!
const date1 = new Date('abc'); console.log(date1); // 👉️ Invalid Date const date2 = new Date('2023-12-45'); console.log(date2); // 👉️ Invalid Date

dealing with invalid dates

If you have difficulties creating a valid Date object, you can pass 2 types of arguments to the Date() constructor:

  1. a valid ISO 8601 string, formatted as YYYY-MM-DDTHH:mm:ss.sssZ , or just YYYY-MM-DD , if you only have a date without time.
  2. multiple, comma-separated arguments that represent the year , month (0 = January to 11 = December), day of the month , hours , minutes and seconds .

# Splitting a Date string to create a valid Date

Here is an example that splits an MM/DD/YYYY formatted string (could be any other format) and passes the values as arguments to the Date() constructor to create a Date object.

Copied!
// 👇️ (MM/DD/YYYY) const str = '09/24/2022'; const [month, day, year] = str.split('/'); console.log(month); // 👉️ 09 console.log(day); // 👉️ 24 console.log(year); // 👉️ 2022 const date = new Date(+year, +month - 1, +day); console.log(date); // 👉️ Sat Sep 24 2022

splitting date string to create valid date

We split the date on each forward slash to get the values of the month, day and year.

Copied!
const str = '09/24/2022'; // 👇️ [ '09', '24', '2022' ] console.log(str.split('/'));

Notice that we subtracted 1 from the month when passing it to the Date() constructor.

This is necessary because the Date constructor expects a zero-based value for the month, where January = 0, February = 1, March = 2, etc.

# Splitting a Date and Time string to create a valid Date

Here is another example, which creates a Date that also contains the hours, minutes and seconds.

Copied!
const str = '09/24/2022 07:30:14'; const [dateValues, timeValues] = str.split(' '); console.log(dateValues); // 👉️ "09/24/2022" console.log(timeValues); // 👉️ "07:30:14" const [month, day, year] = dateValues.split('/'); const [hours, minutes, seconds] = timeValues.split(':'); const date = new Date( +year, +month - 1, +day, +hours, +minutes, +seconds, ); // 👇️️ Sat Sep 24 2022 07:30:14 console.log(date);

splitting date and time string to create valid date

We first split the date and time string on the space, so we can get the date and time components as separate strings.

Copied!
const str = '09/24/2022 07:30:14'; const [dateValues, timeValues] = str.split(' '); console.log(dateValues); // 👉️ "09/24/2022" console.log(timeValues); // 👉️ "07:30:14"

We then had to split the date string on each forward slash to get the value for the month, day and year.

Copied!
const dateValues = '09/24/2022'; console.log(dateValues.split('/')); // 👉️ [ '09', '24', '2022' ]

Note that your separator might be different, e.g. a hyphen, but the approach is the same.

We also split the time string on each colon and assigned the hours, minutes and seconds to variables.

Copied!
const timeValues = '07:30:14'; console.log(timeValues.split(':')); // 👉️ [ '07', '30', '14' ]

We then passed all of the values to the Date() constructor to create a Date object.

Copied!
const date = new Date(+year, +month - 1, +day, +hours, +minutes, +seconds);

If you need to store a date string in your database, it’s best to store the ISO 8601 representation of the date.

# Getting an ISO-formatted date

You can get the ISO formatted date by calling the toISOString() method.

Copied!
const str = '09/24/2022 07:30:14'; const [dateValues, timeValues] = str.split(' '); console.log(dateValues); // 👉️ "09/24/2022" console.log(timeValues); // 👉️ "07:30:14" const [month, day, year] = dateValues.split('/'); const [hours, minutes, seconds] = timeValues.split(':'); const date = new Date( +year, month - 1, +day, +hours, +minutes, +seconds, ); // 👇️️ Sat Sep 24 2022 07:30:14 console.log(date); // 👇️ "2022-09-24T04:30:14.000Z" (ISO 8601) console.log(date.toISOString());

getting iso formatted date

The toISOString method returns a string of the date in the ISO 8601 format according to universal time.

The ISO string can easily be passed to the Date() constructor to create a new Date object.

# Convert a String to a Date using date-fns

You can also use the date-fns module to convert a string to a Date.

First, make sure you have the module installed by running the following command from the root directory of your project.

Copied!
# 👇️ with NPM npm install date-fns # 👇️ with YARN yarn add date-fns

Now you can import and use the parse() function from the date-fns module.

Copied!
import parse> from 'date-fns'; const str = '12/21/2024 06:34:59'; const date = parse(str, 'MM/dd/yyyy hh:mm:ss', new Date()); console.log(date); // 👉️ 2024-12-21T06:34:59.000Z

The code sample assumes that you have a Date string formatted as MM/DD/yyyy hh:mm:ss .

The parse function takes a date or date and time string and converts the string to a Date object.

You can view the accepted format string patterns in this table in the docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью