| by Arround The Web | No comments

How to convert milliseconds to date

One of the many built in features that JavaScript provides is the ability to be able to convert milliseconds into date or vice versa. JavaScript uses the Date() function to perform these tasks. Before we proceed, it is important to note that the values of date and millisecond that the Date() constructor will give us are in reference to a standard starting date “January 1, 1970, 00:00:00 UTC”.

In this article let us take a look at how you can utilise this function to perform the conversions.

Converting Milliseconds to Date

To Convert milliseconds to date you simply need to use “var” or “const” to declare a variable which has the value of the milliseconds stored in it.

var checkTime = 1658736641414;

You can declare a specific integer for the milliseconds or you can use the current millisecond amount. For the current millisecond, use the function getTime() which is used in JavaScript to return the number of milliseconds from the standard date “January 1, 1970, 00:00:00 UTC” till the current date as shown below:

var checkTime = new Date().getTime();

Once the millisecond integer is stored into a variable, use the “Date()” constructor to convert the milliseconds into date and then store it into the new variable “checkDate”.

var checkDate = new Date(checkTime);

console.log(checkDate.toString());

The complete code snippet along with the output is given below for reference:

As shown in this snippet, you will get an output of the date corresponding to the milliseconds that you input into the variable.

Conversion from Date to various String Formats?

Once you have your date in a variable, you can use various string methods to display the date in any format that you prefer. Some common formats are shown below:

toLocaleString()

The following method will return the string in the locale format that your system is using:

checkDate.toLocaleString();

toDateString()

The use of this method will return the string with only the Date and not the time:

checkDate.toDateString();

toTimeString()

The following method will display only the time out of the Date conversion:

checkDate.toTimeString();

Conclusion

To convert milliseconds to date, provide the milliseconds stored in a variable to the Date() constructor and it will perform the conversion. Later, store the result in any variable to use it later. This article represents the step by step guide on how to perform conversions from milliseconds to a date. Moreover, it is demonstrated how to convert the date into different formats using various methods provided by JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply