- “getTime()” method.
- “parse()” method.
The “getTime()” method calculates the number of milliseconds since January 1, 1970 and returns it. This method can be applied to return the number of milliseconds till the specified date.
Let’s overview the following example:
let dateString = '2022-11-11';
let date = new Date(dateString);
console.log("The date is:", date)
let timestamp = date.getTime();
console.log("The converted date string to timestamp in milliseconds is:", timestamp)
console.log("The converted date string to timestamp in seconds is:", timestamp/1000)
Implement the following steps as given in the above code snippet:
- Specify the date string in the first step.
- After that, pass the specified date string as the parameter of the “Date” constructor and display it.
- Next, apply the “getTime()” method to get the value of the time stamp with respect to the specified date string.
- Finally, display the timestamp value in milliseconds and seconds, respectively.
From the above output, it can be observed that the value of the timestamp is retrieved with respect to the specified data string.
The “Date.parse()” method parses a date string and gives the difference of time since 1st January 1970. This method can be applied likewise to compute the value of the timestamp from the specified date as the function’s argument.
In the given syntax:
- “string” corresponds to the string referring to the date.
Let’s move on to the below-stated example:
let get = Date.parse(date);
console.log("The converted date string to timestamp in milliseconds is:", get)
console.log("The converted date string to timestamp in seconds is:", get/1000)
In the above lines of code:
- Declare a function named “timeStamp()” having the date that needs to be converted into a timestamp as its parameter.
- In its definition, pass the function’s parameter to the “parse()” method to compute the value of the time stamp from the passed date.
- Lastly, display the timestamp value in milliseconds and seconds, respectively.
The above output signifies that we have successfully converted the date string to a timestamp.