Typescript convert string to date

How to Convert string to/from Date in Typescript?| Javascript examples

This tutorial is about converting string to/from Date in javascript with examples. These examples work in typescript it is a superset of javascript.

javascript String and Date types

string is an object that holds the sequence of characters enclosed in double-quotes. Date objects have default current date and time in typescript. Date with default constructor returns current date-time. The date object holds different timezones — GMT and UTC .

The string format should be ISO format. ISO format is of YYYY-MM-DDTHH:mm:SS and YYYY-MM-DD .

if you want a timezone like UTC format, suffix z .

String and date are objects in typescript which hold different values.

Sometimes, want to manipulate dates and convert them to/from different types. We have a momentJS library to handle and manipulate Date objects using typescript and javascript.

How to Convert String to Date in typescript?

We have many ways to convert to String to date in typescript, One-way using the date constructor, second-way using the momentjs library.

Читайте также:  Java stream collecting and then

Using Date constructor

It is one of the simple and easy ways to convert to a Date object. Pass string date value to Date constructor.

Return a valid date if a string is in ‘ISO format.’ And returns an invalid date if a string date is not in ISO format .

let dateString = "2015-10-06"; let dateString1 = "10-06-2015"; let dateString2 = "asdfasdfasdfads"; let newDate = new Date(dateString); let newDate1 = new Date(dateString1); let newDate2 = new Date(dateString2); console.log(newDate); // Tue Oct 06 2015 05:30:00 GMT+0530 (India Standard Time) console.log(newDate1); // Tue Oct 06 2015 00:00:00 GMT+0530 (India Standard Time) console.log(newDate2); // Invalid Date

momentjs to convert to Date from String

momentjs library has constructor,

moment(stringDate, formatString);

Arguments: stringDate — valid date in string formatString — Output Date format

string contains date data in the format of MM-DD-YYYY then we have to use the method for converting to a Date object.

var dateString = "08-25-2018"; var momentVariable = moment(dateString, "MM-DD-YYYY"); var stringvalue = momentVariable.format("YYYY-MM-DD"); console.log(stringvalue); // outputs 2018-08-25

How to convert Date to String in typescript

We have many ways to convert Date to String in typescript, One way using the toDateString() method constructor, second way using momentjs library. We will see both below with examples.

Using toDateString() method

Date object one method called toDateString() that returns a date in the form of a string.

Here is an example of Converting from Date to String

var date = new Date("2017-03-07T10:00:00"); let str = date.toDateString(); console.log(str); //Tue Mar 07 2017 console.log(typeof str); // string

Using momentjs example

A date object is created, passing this date object to the moment constructor and calling the format method that parses the date as per the format described.

var date = new Date("2017-03-07T10:00:00"); var formatted = moment(date).format("D MMMM YYYY"); console.log("formatted", formatted); // outputs 7 March 2017 console.log("formatted", typeof formatted); // outputs string

ES6 toLocaleDateString toLocaleTimeString methods

ES6 introduced toLocaleDateString and toLocaleTimeString to the Date object.

The toLocaleDateString method converts the current date with localized format into a String.

const date = new Date(); const localDateString = date.toLocaleDateString('En-en'); console.log(localDateString); //6/18/2021 console.log(type localDateString); // string The toLocaleTimeString method converts the current time with localized format into String.
const date = new Date(); const localDateString = date.toLocaleTimeString('En-en'); console.log(localDateString); //8:50:29 PM console.log(type localDateString); // string

Conclusion

To sum up, We learned multiple ways to convert String to Date and Date to String in Javascript and typescript.

Источник

Typescript convert string to date

Last updated: Jan 23, 2023
Reading time · 5 min

banner

# Table of Contents

# Convert a String to a Date object in TypeScript

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

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

Copied!
const str = '2024-07-21'; const date = new Date(str); console.log(date); // 👉️ 2024-07-21T00:00:00.000Z console.log(date.toDateString()); // 👉️ Sun Jul 21 2024

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

# Make sure your Date string is valid

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 str = '07_21_2024'; const date = new Date(str); console.log(date); // 👉️ Invalid Date

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 parameters that represent the year , month (0 = January to 11 = December), day of the month , hours , minutes and seconds .

# Getting date components from a date string

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

Copied!
const str = '07/21/2024'; const [month, day, year] = str.split('/'); console.log(month); // 👉️ "07" console.log(day); // 👉️ "21" console.log(year); // 👉️ "2024" const date = new Date(+year, +month - 1, +day); console.log(date); // 👉️ 2024-07-20T21:00:00.000Z

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

Copied!
const str = '07/21/2024'; // 👇️ [ '07', '21', '2024' ] console.log(str.split('/'));

We used the unary plus (+) operator to convert the values to numbers.

Copied!
console.log(+'21'); // 👉️ 21 console.log(typeof +'21'); // 👉️ number

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

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

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

# Getting date and time components from a date-time string

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

Copied!
const str = '07/21/2024 04:24:37'; const [dateComponents, timeComponents] = str.split(' '); console.log(dateComponents); // 👉️ "07/21/2024" console.log(timeComponents); // 👉️ "04:24:37" const [month, day, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, +month - 1, +day, +hours, +minutes, +seconds); // 👇️ Sun Jul 21 2024 04:24:37 console.log(date);

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

We then had to split the date string on each forward slash / to get the value for the month, day and year. 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.

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

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 = '07/21/2024 04:24:37'; const [dateComponents, timeComponents] = str.split(' '); console.log(dateComponents); // 👉️ "07/21/2024" console.log(timeComponents); // 👉️ "04:24:37" const [month, day, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, +month - 1, +day, +hours, +minutes, +seconds); // 👇️ Sun Jul 21 2024 04:24:37 console.log(date); // 👇️ "2024-07-21T01:24:37.000Z" console.log(date.toISOString());

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 in TypeScript using date-fns

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

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 = '09-24-2024 09:44:21'; const date = parse(str, 'MM-dd-yyyy hh:mm:ss', new Date()); console.log(date); // 👉️ 2024-09-24T06:44:21.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.

# Convert a String to a Date in TypeScript using moment.js

You can also use the moment package to convert a string to a date in TypeScript.

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 moment # 👇️ with YARN yarn add moment

Now you can import and use the moment module to convert a string to a date object.

Copied!
import moment from 'moment'; const str = '09-24-2024 09:44:21'; const date = moment(str, 'MM-DD-YYYY hh:mm:ss').toDate(); console.log(date); // 👉️ 2024-09-24T06:44:21.000Z

Notice that I used the toDate() method to convert the moment object to a JavaScript date.

You can remove the call if you’d rather keep it as a moment object.

Note that the moment module should generally only be used when your project already relies on it.

In general, it’s better to use the more modern date-fns package because it is much faster.

# 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.

Источник

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