JavaScript: Convert Milliseconds to Date

While working with dates in JavaScript, we often need to convert milliseconds to a date value as we need to process them. This article will write functions to convert timestamps to human dates.

Convert Milliseconds to a Date Value using toDateString()

Javascript’s toDateString() method will return the portion of Date in English in the format:

  • First four letters for the day of the weekday.
  • First three letters of the month’s name.
  • Two digits of the day of the month.
  • Four digits for the year.

Example:-

convert 1647540106902 milliseconds to date

Code:-

Advertisements
// function to convert milliseconds to date value 
function convertMilliSecondsToDate(_milliSeconds)
{
return (new Date(_milliSeconds)).toDateString();
}
// usage of the function
//getting the milliseconds value
console.log(convertMilliSecondsToDate(1647540106902));

Output:-

Thu Mar 17 2022

Explanation:-

  • Here, we use toDateString() method to convert the milliseconds to a date value.

Convert Milliseconds to a Date Value by Accessing Properties of a Date

Javascript’s getFullYear() method will return the year of the date specified according to the local time.

Javascript’s getMonth() method will return the month of the date specified according to the local time. The month value is zero-based that is zero indicates the first month of the year.

Javascript’s getDate() method will return the day of the month of the date specified according to the local time.

Javascript’s getTime() method will return the milliseconds of a particular date value since ECMAScript epoch

Example:-

convert 1647540106902 milliseconds to date

Code:-

// function to convert milliseconds to date value 
function convertMilliSecondsToDate(_milliSeconds)
{

var dateVal=new Date(_milliSeconds).getDate();
var monthFromDate=new Date(_milliSeconds).getMonth()+1;
var yearFromDate=new Date(_milliSeconds).getFullYear();
return monthFromDate+'/'+dateVal+'/'+yearFromDate;
}
// usage of the function
//getting the milliseconds value
console.log("Date Value: " + convertMilliSecondsToDate(1647540106902));

Output:-

Date Value: 3/17/2022

Explanation:-

  • Here, we access different properties of the date.
  • The new Date(_milliseconds) value will give the corresponding date object for the milliseconds in variable dateObj.
  • To convert the dateObj to your desired format we access different properties of Date.
  • getFullYear() method gets the year from the dateObj.
  • getMonth() method receives the current month from the dateObj.
  • getDate() method receives the day from the dateObj.
  • After accessing all the above values, concatenate them to get the value in the desired format.

I hope this article helped you convert milliseconds to a javascript date. Good Luck !!!

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top