FOR DEVELOPERS

How to Convert String to Date in JavaScript

Convert String to Date in JavaScript

“Date” is a relatively fundamental concept. We frequently use it and so do computers. It is always included in records saved in databases because it is an essential piece of information. It is imperative that you, as a programmer or web developer, understand the basics of converting a string to date in JavaScript or whichever language you use. For the purpose of this article, however, we’ll be focusing on JavaScript.

Converting a string to a Date object

There are five different ways to change a date value from a string data type to a date type.

  • By using the Date() function in JavaScript.
  • By using parse(), UTC() which are static methods of the Date construct.
  • The given string date can alternatively be divided into three components, each of which represents the date, month, and year, before being converted to a valid Date format.
  • By using Date object to string conversion with the toDateString() method.

Let’s explore these methods in some detail.

New Date() constructor

JavaScript has a constructor called the Date constructor. This function can be used to retrieve the local system's current date and time. Additionally, you can change a date value from a string data type to a Date data type with the constructor. Let's take a quick look at this element.

Syntax

new Date()
new Date(year, month, day)
new Date(month, day, year)

Date()

Parameters

A string containing a date in the ISO 8601 calendar date extended format should be provided as the first argument to the constructor of the Date class.

Return value

The date format is used for the return type. More precisely, the return value contains a number that is just the number of milliseconds from January 1, 1970, 00:00:00 UTC, and the date that was obtained by parsing the supplied string representation of the date. This function returns "Invalid Date" if the parameters are not in the correct format.

Example:

// create a date variable
const date1 = new Date("2022,11,19");
console.log(date1); // print the date

const date2 = new Date("2022,11,19"); console.log(date2); // print the date

// passing wrong date parameters const date3 = new Date("19,11,2022"); console.log(date3); // print the date

Output:

Sat Nov 19 2022 00:00:00 GMT+0100 (West Africa Standard Time)
Sat Nov 19 2022 00:00:00 GMT+0100 (West Africa Standard Time)
Invalid Date

The illustration demonstrates how to use the constructor of the Date class to transform a date from a string to a Date object.

Date.parse() constructor

Another way to convert a date from string to Date format is provided by the date constructor. A static method called parse exists here. It parses a date represented as a string and returns the duration in milliseconds, disregarding leap seconds.

Syntax

Date.parse(year, month, day)

Parameters

The parse method of the date constructor also requires a string parameter that provides a date in the ISO 8601 calendar date extended format.

Return value

The text representation of the date is parsed to produce a date, which is returned together with an integer containing just the milliseconds from January 1st, 1970, 00:00:00 UTC. This function returns NaN if the parameters are not provided in the proper format.

Example:

// create a date variable 
const date1 =  Date.parse("2022,12,25");
console.log(date1); // print the date

const date2 = Date.parse("2020,09,10"); console.log(date2); // print the date

// passing wrong date parameters const date3 = Date.parse("29,10,2023"); console.log(date3); // print the date

Output:

1671922800000
1599692400000
NaN

The example above demonstrates how to use the static function parse of the Date constructor to transform a date from a string to a Date object.

Date.UTC() constructor

Similar to the Date.parse() constructor, the static function Date.UTC() also accepts parameters. However, they are treated as UTC. It returns the number of milliseconds that have elapsed since January 1 at 0:00 UTC.

Syntax

Date.UTC(year, month, day)

Parameters

There must be a string that represents a date in the expanded ISO 8601 calendar date format.

Return value

The milliseconds between January 1, 1970, 00:00:00, universal time, and the supplied date and time are returned by UTC(), which accepts a comma-delimited date and time inputs.

Example:

// create a date variable 
const dateUTC = new Date(Date.UTC(2022, 11, 3, 0, 0, 0));
console.log(dateUTC): // print the date

Output:

Sat Dec 03 2022 01:00:00 GMT+0100 (West Africa Standard Time)

The example demonstrates how to use the static function UTC of the Date constructor to transform a date from a string to a Date object. UTC() is a static method but cannot be considered a method for a date instance’s function.

Split method to convert string to Date

You have seen three functions up to this point, but all of them need the input supplied to them to be in the ISO 8061 extended format. However, you cannot always be assured that the input is in the said format. What should you do if this is the case? The split method is the answer.

You can once more utilize the Date constructor, which accepts specified input, to transform the string to the Date format.

Syntax

new Date(year,Month, day)

Parameters

The data type for all of the parameters should be an integer.

Enter the year value with all 4 digits. It will be presumed that you meant to put "20" as "2020" rather than "1920." The month value begins at zero. Consequently, you need to deduct 1 from the month's value. For example, May should be entered as 4, not 5. Thus, the range of acceptable values is 0 to 11. The date can be entered in a typical manner. The date value ranges from 1 to 31.

Return value

An object of the Date constructor makes up the return. The result satisfies all the requirements for converting a date value from a string to a date format using the Date class. This is so because both of these are constructors for the Date class and return an object of the Date class.

Example:

year = 2023
month = 1
day = 19
// create a date variable 
var date = new Date(2023, 1, 19);
// print the date
console.log(date);

Output:

Sun Feb 19 2023 00:00:00 GMT+0100 (West Africa Standard Time)

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.

Converting string to Date in JavaScript using third-party libraries

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. We’ll focus on Moment.js in this article.

Moment.js

Using Moment.js, you need to modify the format of a date given by the user. You can utilize the moment().format() function to implement this functionality. A moment (date) can be produced from a string using the moment().format() method.

Syntax

moment().format(string);

Parameter

The format is specified by a single string type parameter that is accepted by this function.

Return value

This function returns the value of the string as a date type.

Example:

// create a date variable 
var date1 = moment().format('MMMM Do YYYY, h:mm:ss a');
console.log(date1)

Output:

January 28th 2023, 11:55:11 pm

Date object to string conversion with toDateString() method

The methods previously covered were concerned with changing a date value from a String data type to a Date data type. But occasionally, you might also require the opposite. You may need to store a date in a database, which is a more frequent and repeating event. As already indicated, the date value is typically stored in databases as a String data type.

Let’s look at how to change the date value's data type from Date to String. There is a method for this in the date class as well.

Syntax

toDateString();

Parameter

There are no parameters for the toDateString() function. It operates on the item that it was called from.

Return value

A string that represents the date object in English is the return value. The returned string has the following structure:

  • The first three letters of the day of the week.
  • The first three letters of the name of the month.
  • Two digits of the month, with zero attached on the left, if required.
  • A four-digit year (at least), possibly with zeros padding the left.

Example:

// create a date variable
const date = new Date(2022, 6, 20, 14, 28, 7);
// the time will be neglected
console.log(date.toDateString());

Output:

Wed Jul 20 2022

If you want to get the time separately from the date, use toTimeString().

Example:

// create a date variable
const date = new Date(2022, 6, 20, 14, 28, 7);
// the time will be neglected
console.log(date.toTimeString());

Output:

14:28:07 GMT+0100 (West Africa Standard Time)

If you would like to get both the date and time attached together, use toString().

Example:

// create a date variable
const date = new Date(2022, 6, 20, 14, 28, 7);
// the time will be neglected
console.log(date.toString());

Output:

Wed Jul 20 2022 14:28:07 GMT+0100 (West Africa Standard Time)

Handling invalid dates

If you create a Date object and get an invalid date, you must correctly format the string before sending it to the Date() constructor.

Example:

// passing wrong date parameters
const date3 = new Date("19,11,2022");
console.log(date3); // print the date

//Output Invalid Date

You can provide two different types of arguments to the Date() constructor if you have trouble constructing a legitimate Date object:

  • A string that is compliant with ISO 8601, structured as YYYY-MM-DDThh:mm:ss.ssTZD or just YYYY-MM-DD if you only have a date without a time.
  • The year, month (0 = January to 11 = December), day of the month, hours, minutes, and seconds are each represented by a comma-separated list of arguments.

Importance of converting string to Date in JavaScript

Converting string to date in JavaScript.webp

There are several reasons why converting a string to a date in JavaScript is important:

  • Data validation: It allows for proper data validation. This ensures that the date entered by the user is in the correct format and is valid.
  • Data manipulation: Once a string is converted to a date, it can be manipulated and used for various purposes, such as date arithmetic, date comparison, etc.
  • Timezone and localization: It allows for proper handling of timezone and localization. This ensures that the date is displayed correctly for different users in different time zones.
  • Formatting: It allows for proper formatting of the date. This makes sure that the date is displayed in the desired format, such as "MM/DD/YYYY" or "DD-MM-YYYY".
  • Interoperability: It also allows for interoperability between different systems and languages. This facilitates easy exchange of date-related data between different systems and languages.
  • Sorting and filtering: When data is represented as a date object, it can be sorted and filtered easily.

In summary, converting a string to a date in JavaScript is important for data validation, manipulation, timezone and localization handling, formatting, interoperability, and sorting and filtering.

Conclusion

There are many options for turning a date string into a JavaScript date object. You can do it yourself or pass portions of the date string directly into the Date constructor. Or, to make the task simpler, you can use a third-party library like Moment.js, Date-fns, etc., to achieve your goal.

Author

  • How to Convert String to Date in JavaScript

    Ejiro ThankGod .U

    Ejiro ThankGod is a skilled web developer and technical writer with over 2 years of expertise in the field. He is passionate about building beautiful, intuitive websites and web applications. As a web developer, Ejiro is proficient in a number of Programming languages, including Python and JavaScript, as well as web development frameworks like React.

Frequently Asked Questions

The JavaScript function used to convert a string to a date object is new Date(string).

Yes, there is a difference. The new Date() constructor creates a date object from the current date and time, while the Date.parse() method creates a date object from a specified date string. The two methods can produce different results depending on the input.

Yes, you can use the new Date(year, monthIndex, day) constructor for the same. Note that the monthIndex parameter is zero-based, meaning January is 0 and December is 11.

The correct format is: "YYYY-MM-DD" or "YYYY/MM/DD".

Yes, you can use various JavaScript methods, such as getFullYear(), getMonth(), getDate(), etc., to extract the different components of the date object and then concatenate them to form a string in the desired format.

ou can use the new Date(Date.UTC()) constructor to create a date object in UTC and then convert it to the local time zone using the toLocaleString() method.

You can use the Date.parse() method to convert a string in a different format to a date object. For example: new Date(Date.parse("Aug 9, 1999")).

You can use a JavaScript library like Moment.js to handle date parsing and formatting of non-standard formats. Alternatively, you can manually parse the string using string manipulation techniques or regular expressions.

It depends on the user's browser settings and the options passed to the method. It can display the date and time in various formats, including long date, short date, long time, short time, and combinations of these.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.