Convert Unix timestamp to Date time with JavaScript

The Unix timestamp value conversion with JavaScript mainly requires when the API request-response contains the date-time value in Unix format and requires showing it on the screen in a user-readable form.

Convert Unix timestamp to Date time with JavaScript


Contents

  1. HTML & Script
  2. Demo
  3. Conclusion

1. HTML & Script

HTML

I created a textbox and a button that call convert() function when gets clicked.

Show converted date time value in <span id='datetime'>.

<input type='text' value='1490028077' id='timestamp'>&nbsp;
<input type='button' id='convert' value='Convert' onclick='convert();'>

<br><br>
<span id='datetime'></span>

Script

Define a convert() function.

From the function perform the following actions –

  • Get inputted Unix timestamp value from the textbox.
  • Define a months_arr Array which is being used in creating formatted date.
  • Convert the value from seconds to milliseconds by multiplying it to 1000 and create a date object.
  • Use inbuilt methods to get year, month, day, hours, minutes, and seconds.
  • Set the formatted date time value to <span> element.
function convert(){

   // Unixtimestamp
   var unixtimestamp = document.getElementById('timestamp').value;

   // Months array
   var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

   // Convert timestamp to milliseconds
   var date = new Date(unixtimestamp*1000);
 
   // Year
   var year = date.getFullYear();

   // Month
   var month = months_arr[date.getMonth()];

   // Day
   var day = date.getDate();

   // Hours
   var hours = date.getHours();

   // Minutes
   var minutes = "0" + date.getMinutes();

   // Seconds
   var seconds = "0" + date.getSeconds();

   // Display date time in MM-dd-yyyy h:m:s format
   var convdataTime = month+'-'+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
 
   document.getElementById('datetime').innerHTML = convdataTime;
 
}

2. Demo

View Demo


3. Conclusion

You can either convert your Unix timestamp value on the server-side while returning the response or you can use the above script to do it on the client side.

If you found this tutorial helpful then don't forget to share.