How To Get Unix Timestamp From A Date String In JavaScript

The Unix timestamp of a date is the number of seconds from Jan 1, 1970, 00:00:00 to that point. Read the full article to learn how to get Unix timestamp from a date string in JavaScript. Let’s get started.

How to get Unix timestamp from a date string in JavaScript

We will share solutions to get Unix timestamp from a date string using the getTime(), valueOf(), and Date.parse() methods.

Using the getTime() or valueOf() method

Assuming you have a date string, here are the steps you need to take to get Unix timestamp from this date string using the getTime() or valueOf() method.

First, we convert the date string into a date object using the new Date() method. Interestingly, this method will self-diagnose the format of the input string.

Click here to read more about the new Date() method and the arguments passed to it.

After initializing the date object from the date string, we will use the getTime() or valueOf() method to get the number of milliseconds since Jan 1, 1970, 00:00:00 of this object.

Divide the number of milliseconds just received by 1000. And we will get the Unix timestamp of the input date string.

Example:

// Initialize a date object from a date string of ISO 8601 format (YYYY-MM-DD)
const date = new Date("2022-12-31");

// Get the Unix timestamp using the getTime() method
const timestamp1 = date.getTime();
console.log("Using the getTime() method: " + timestamp1 / 1000);

// Get the Unix timestamp using the valueOf() method
const timestamp2 = date.valueOf();
console.log("Using the valueOf() method: " + timestamp2 / 1000);

Output:

Using the getTime() method: 1672444800
Using the valueOf() method: 1672444800

Using the Date.parse() methods

We will use the Date.parse() method in this solution. The Date.parse() method parses the date string and returns the number of milliseconds since Jan 1, 1970, 00:00:00. If the input date string is invalid, the Date.parse() method will return NaN.

Syntax:

Date.parse(dateString)

Parameter:

dateString: a date string.

After we use the Date.parse() method to parse the date string and get the number of milliseconds since Jan 1, 1970, 00:00:00. We divide the number of milliseconds we just got by 1000 to get the Unix timestamp of the input date string.

Example:

// Get the number of milliseconds since Jan 1, 1970, 00:00:00
const timestamp = Date.parse("2022-12-31");

// Return NaN
// const timestamp = Date.parse("2022-31-12");

// Get the Unix timestamp
console.log("Using the Date.parse() method: " + timestamp / 1000);

Output:

Using the Date.parse() method: 1672444800

Summary

To get Unix timestamp from a date string in JavaScript, you can call the getTime() or valueOf() method on a date object initialized from the date string. You can also do this with the Date.parse() method without instantiating a new date object. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *