How to Convert String to Date in TypeScript?

There will be times when you need to convert string to date in Typescript. In this Typescript tutorial, I will explain how to convert string to date in TypeScript using different methods with examples.

I will also show you the below examples:

  • Convert String to Date Format dd/mm/yyyy in TypeScript
  • How to convert string to date format dd/mm/yyyy in Typescript
  • Convert string to date with timezone in Typescript
  • Convert string to date without timezone in Typescript
  • Typescript: convert iso string to date
  • Typescript: convert utc string to date
  • Typescript: moment convert string to date

To convert a string to a Date object in TypeScript, you can use the Date constructor directly if the string is in a recognized date format. For example, let newDate = new Date(‘2024-02-02T00:00:00’); will create a new Date object. Alternatively, for strings in different formats, you can use Date.parse() like so: let newDate = new Date(Date.parse(‘Feb 2, 2024’)); which first parses the string into milliseconds and then converts it to a Date object.

How to Convert String to Date in TypeScript

To convert a string to date in Typescript, you can use any of the below 3 methods. Let us explore each method with examples.

1. Using the Date constructor

The most straightforward way to convert a string to a date in TypeScript is by using the Date constructor. If the string is in a recognized format (such as ISO 8601), the Date constructor can parse it directly. Here is an example.

let dateString: string = '2025-02-02T00:00:00';
let newDate: Date = new Date(dateString);
console.log(newDate);

This will output a Date object representing the date and time specified in the string. Here you can see the output in the screenshot below; I executed the code using this command – ts-node TypescriptExamples.ts

Convert String to Date in TypeScript

2. Using Date.parse()

Another way to convert a string to a date is by using the Date.parse() method, which parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can then use these milliseconds to create a new Date object.

let dateString: string = 'February 2, 2024';
let dateMillis: number = Date.parse(dateString);
let newDate: Date = new Date(dateMillis);
console.log(newDate);

This will also give you a Date object for the given date string.

Here is the output, I executed the code using VS code:

typescript convert string to date

3. Using libraries like moment.js

In Typesctipt, to convert a string to date, you can also use various 3rd party libraries like moment.js. While not a TypeScript-specific method, it works well in TypeScript projects.

First, you need to install moment.js:

npm install moment --save

Then, you can use it to convert a string to a date:

import * as moment from 'moment';

let dateString: string = '02-02-2025';
let newDate: moment.Moment = moment(dateString, 'MM-DD-YYYY');
console.log(newDate.toDate());

This will convert the string to a moment.Moment object, and you can use .toDate() to get a JavaScript Date object.

Converting a string to a Date object in TypeScript is fairly simple, whether you use the Date constructor, Date.parse() method or a library like moment.js.

Now, let us check a few more examples related to “Typescript convert string to date”.

Convert String to Date Format dd/mm/yyyy in TypeScript

To convert a string to a Date object in TypeScript and then format it as “dd/mm/yyyy”, you can use the Date object to parse the string and then format the date using toLocaleDateString method with appropriate options.

Here’s an example of how to convert a string to date in dd/mm/yyyy format in Typescript.

// Assume we have a date string in the format "dd-mm-yyyy"
let dateString: string = "02-02-2024";

// First, split the string to extract the parts
let dateParts: string[] = dateString.split("-");

// Create a new Date object using the parts (note: month is 0-indexed in JavaScript Dates)
let dateObject: Date = new Date(+dateParts[2], +dateParts[1] - 1, +dateParts[0]);

// Format the date as "dd/mm/yyyy"
let formattedDate: string = dateObject.toLocaleDateString("en-GB", {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
});

console.log(formattedDate); // Outputs: "02/02/2024"

In this example, we start by splitting the input string into its constituent parts (day, month, and year). We then use these parts to create a Date object. JavaScript Date months are zero-indexed (i.e., January is 0, February is 1, etc.), so we subtract 1 from the month part.

Finally, we use toLocaleDateString with the “en-GB” locale, which uses the day/month/year format, and specify options to ensure we get two-digit days and months and a four-digit year.

You can see the output in the screenshot below:

typescript convert string to date format dd/mm/yyyy

Typescript Convert String to Date with Timezone

When working with dates in TypeScript, it may become necessary to convert a string representing a date and time to a Date object according to a specific timezone. This process ensures that one can handle dates consistently across different locales.

Utilizing the Date Constructor

The Date constructor can parse a date string and return a Date object in local time. However, to account for timezones, one can make use of libraries like moment-timezone or manipulate the date string directly before parsing.

import * as moment from 'moment-timezone';

let dateString: string = '2024-01-31T15:00:00Z'; // UTC time
let timezone: string = 'America/Los_Angeles'; // Desired timezone

let date: Date = moment.tz(dateString, timezone).toDate();

Applying Date.prototype.toLocaleString

Alternatively, one can convert the local date to a string in the desired timezone:

const eventDate = new Date('2024-01-31T15:00:00Z');
const timezone = 'America/Los_Angeles';

const localDate = eventDate.toLocaleString('en-US', { timeZone: timezone });

After obtaining the local date string representation, one could parse it back into a Date object if needed.

Custom Function Approach

One may opt to define a custom function utilizing the Intl.DateTimeFormat object. This approach gives granular control over the output format and parsing:

function convertTZ(dateString: string, tzString: string): Date {
  return new Date(new Date(dateString).toLocaleString('en-US', { timeZone: tzString }));
}

let date: Date = convertTZ('2024-01-31T15:00:00Z', 'America/Los_Angeles');

In all methods, it is vital to ensure that the date string is in a recognized format, such as ISO 8601, to avoid inconsistencies across different environments.

TypeScript Convert String to Date Without Timezone

When converting a string to a date in TypeScript, a common issue developers face is dealing with timezones. To ensure that a string is converted to a Date object without considering the timezone, one can manipulate the string or use specific JavaScript methods that ignore timezone information.

Using String Manipulation

To transform a date string to a Date object without applying the timezone, one might add a ‘Z’ at the end of the string to indicate UTC time:

let dateString = '2024-01-31T10:00:00';
dateString += 'Z'; // Indicates that the time is in UTC
const date = new Date(dateString);
console.log(date.toISOString()); // Outputs: "2024-01-31T10:00:00.000Z"

Applying a Custom Function

Developers can write a custom function to parse the date components and construct a new Date object:

function convertToDate(string: string): Date {
  const parts = string.match(/(\d+)/g);
  return new Date(Date.UTC(
    parseInt(parts[0], 10),
    parseInt(parts[1], 10) - 1, // Month is 0-indexed
    parseInt(parts[2], 10),
    parseInt(parts[3], 10),
    parseInt(parts[4], 10),
    parseInt(parts[5], 10)
  ));
}

const dateObject = convertToDate('2024-01-31 10:00:00');
console.log(dateObject.toISOString()); // Expected format without timezone conversion

This approach ensures that the time is treated as UTC and not converted to the local time of the environment running the code.

Note on Timezone Neutral Dates

If one wants the time to represent a ‘timezone-neutral’ date and time, it’s necessary to avoid automatic conversion to or from local time. The methods demonstrated above can assist in maintaining the original time specification without an offset.

Typescript Convert String to DateTime Format

In TypeScript, one can convert a string to a Date object in several ways. The Date constructor in JavaScript is widely used for this purpose, and TypeScript, being a superset of JavaScript, follows the same approach.

Direct Usage of the Date Constructor: One can directly pass a string to the Date constructor. However, the string should be in a format recognized by the Date.parse method, such as YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

const dateString = '2024-01-31T09:45:00';
const dateObject = new Date(dateString);

Manually Parsing the Date String: If the date string is in a custom format, one might need to parse the string manually and then use the Date constructor with individual arguments for year, month, and day.

let dateStr = '20240131'; // Custom format: YYYYMMDD
let year = parseInt(dateStr.slice(0, 4));
let month = parseInt(dateStr.slice(4, 6)) - 1; // Month is 0-indexed
let day = parseInt(dateStr.slice(6, 8));
let date = new Date(year, month, day);

Using Third-Party Libraries: To handle more complex scenarios and formats, developers often resort to libraries like moment.js or date-fns, which offer robust parsing and formatting options.

// Using moment.js
import * as moment from 'moment';
const date = moment('2024-01-31', 'YYYY-MM-DD').toDate();

Remember that the Date object in TypeScript is built on top of the Date object in JavaScript, and therefore inherits all of its features and capabilities, including its quirks and inconsistencies. One should always pay attention to time zones and locale differences when working with dates.

TypeScript Convert ISO String to Date

In TypeScript, ISO date strings can be transformed into Date objects using the native JavaScript Date constructor. An ISO date string follows a standardized format (ISO 8601) that represents a specific point in time. Below is a method demonstrating this conversion.

Example:

const isoDateString = '2021-12-15T13:45:30Z'; // An example ISO string
const dateObject = new Date(isoDateString);
console.log(dateObject);

Explanation:

  • The Date constructor parses the ISO string.
  • The resulting dateObject is a Date instance representing the specified time.

When handling time zones in ISO strings, the Date object automatically adjusts to the local time zone. Be cautious with time zones to avoid unexpected offsets.

Edge Cases:

  • An invalid ISO string throws an error during conversion.
  • The time zone, if omitted, is assumed to be UTC.

Best Practices:

  • Use built-in methods over external libraries for simplicity.
  • Validate ISO strings before conversions to prevent run-time errors.

Note: While the native Date object suffices for basic cases, complex date manipulations might warrant the use of libraries such as date-fns or Moment.js.

To ensure robustness, developers often encapsulate the conversion in a function that includes error handling and optional customization for specific use cases.

TypeScript Convert UTC String to Date

When dealing with time in JavaScript and TypeScript, it is essential to correctly handle time zones. To convert a UTC string to a date in TypeScript, one can use the Date constructor. It is straightforward and does not require any third-party libraries.

First, ensure the UTC string is in ISO format, such as YYYY-MM-DDTHH:MM:SSZ. The final Z indicates that the time is in UTC.

const utcString = '2024-01-31T14:00:00Z';
const dateObject = new Date(utcString);

In this example, dateObject is now a Date instance representing the time provided in the UTC string.

For strings that do not specify timezone information (i.e., lacking a Z or offset), parsing may result in a date and time in the local time of the code execution environment. To parse as UTC, append 'Z' to the string:

const localString = '2024-01-31T14:00:00';
const utcDateObject = new Date(`${localString}Z`);

Key Points:

  • Use ISO format UTC strings with a trailing Z for UTC time.
  • The Date constructor in TypeScript interprets the string as UTC if it ends with Z.
  • Avoid timezone-related issues by specifying the correct string format.

Typescript Moment Convert String to Date

Converting strings to dates in TypeScript can be streamlined with libraries such as Moment.js or Date-fns. Each offers functions tailored for seamless conversions.

Moment.js and Date-fns

Moment.js:

  • It has been a widely used library for managing and converting dates in JavaScript and TypeScript.

Date-fns:

  • Provides a suite of functions similar to Moment.js but with a focus on a modular approach, allowing developers to import only the functions they need.

Using Library Functions for Conversion

Moment.js:

  1. Use moment() to create a date object from a string.
import moment from 'moment';

const dateString = "2024-01-31";
const date = moment(dateString).toDate();
  1. Define the format of the input string if it’s non-standard.
const date = moment(dateString, "YYYY-MM-DD").toDate();

Date-fns:

  1. Utilize parseISO for ISO formatted strings.
import { parseISO } from 'date-fns';

const dateString = "2024-01-31";
const date = parseISO(dateString);
  1. For custom formats, use parse.
import { parse } from 'date-fns';

const dateString = "31-01-2024";
const dateFormat = "dd-MM-yyyy";
const date = parse(dateString, dateFormat, new Date());

Conclusion

While working with strings and dates in Typescript, you will get various requirements to convert strings to date in Typescript using various methods. In this Typescript tutorial, we discussed various methods to convert a string to a date in Typescript.

  1. Using the Date constructor
  2. Using Date.parse()
  3. Using libraries like moment.js

Apart from this, I have also explained the examples below related to Typescript string-to-date conversion.

  • convert string to date without timezone in typescript
  • Typescript convert string to date format dd/mm/yyyy
  • Typescript: convert string to date with timezone
  • Typescript: convert string to date without timezone
  • Typescript: convert string to datetime format
  • Typescript: convert iso string to date
  • Typescript: convert utc string to date
  • Typescript moment convert string to date

You may also like:

>