How to Convert a Date String to Timestamp in JavaScript ?
Last Updated :
07 Dec, 2023
In this article, we are going to learn about the conversion of Date strings to Timestamps by using JavaScript. Converting date strings to timestamps means translating human-readable date representations into numeric values, indicating the time’s position in milliseconds since January 1, 1970.
Several methods can be used to Convert a Date String to Timestamp in JavaScript, which are listed below:
Approach 1: Using Date.parse() Method
The date parse() Method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide.
Syntax:
Date.parse( datestring );
Example: In this example, we are using the above-explained method.
Javascript
let dateString = "2023-08-23T12:34:56" ;
let result = Date.parse(dateString);
console.log(result);
|
Approach 2: Using new Date() and getTime() Methods
In this approach, using new Date() creates a date object from a string, then .getTime() extracts the Unix timestamp (milliseconds since 1970).
Syntax:
Date.getTime()
Example: In this example, the date string “2023-08-23T12:34:56” is first converted into a Date object using new Date(). Then, the .getTime() method is used to obtain the Unix timestamp value
Javascript
let dateString = "2023-08-23T12:34:56" ;
let date = new Date(dateString);
let result = date.getTime();
console.log(result);
|
In this approach, we are using Date.parse() and Unary Plus to Converts date string to Unix timestamp by parsing with Date.parse() and converting result to numerical timestamp using the unary plus operator.
Syntax:
let result = +Date.parse(dateString);
Example: In this example, we are using the above-explained approach.
Javascript
let dateString = "2023-08-23T12:34:56" ;
let result = +Date.parse(dateString);
console.log(result);
|
In this approach, we are using Date.valueOf() to Converts date string to Unix timestamp by creating a Date object and using its .valueOf() method for numerical timestamp representation.
Syntax:
dateObj.valueOf()
Example: In this example we are using the above-explained apporach.
Javascript
let dateString = "2023-08-23T12:34:56" ;
let result = new Date(dateString).valueOf();
console.log(result);
|
In this approach, we are using moment.js’s unix() method for getting the timestamp of the given date.
Example: In this example, we are using moment.js’s unix() method.
Javascript
const moment = require( 'moment' );
let date = "05/12/2023 17:59:56" ;
let result = moment(date).unix();
console.log( "Result:" , result)
|
Output:
1683894596
Share your thoughts in the comments
Please Login to comment...