Epoch and Date Time Conversion in JavaScript


The Date Time has important role in web programming. The JavaScript is a powerful client end scripting language to handle date time. With JavaScript, we can create date time pickers to pick date time, create event calendars, create timers, clock or create schedulers. We can also get epoch or unix timestamp from dates or can convert unix timestamp to human readable dates using JavaScript.

Here we will explain JavaScript Date Time Objects and functions to get current epoch or unix timestamp, convert timestamp to date and convert date to epoch or unix timestamp.


Get current date and time in JavaScript

The JavaScript Date() function return object of current date and time.

var date = new Date();	

The Date() object’s constructor accepts many types of format to get epoch or timestamp. We can pass human readable formats to get date object.

var date = new Date("Wed, 27 March 2019 13:30:00");
var date = new Date("Wed, 27 July 2019 07:45:00 GMT");	
var date = new Date("27 July 2019 13:30:00 GMT+05:30");

Get Epoch or Unix Timestamp in JavaScript

We can get current epoch or unix timestamp in JavaScript using Date() objects and getDate() function.

var date = new Date();
var timestamp = date.getTime();

The getTime() function returns timestamp in milliseconds. We can get current unix timestamp in seconds using below code.

var date = new Date();
var timestamp = Math.floor(date.getTime()/1000.0);

Convert Epoch or Unix timestamp to Human Readable Date in JavaScript

We can easily convert unix timestamp to human readable date using date() object

var unixTimestamp = 1553617238;
var date = new Date(unixTimestamp*1000);	

Get Curent Day, Month, Year in JavaScript

We can current Date, Month and year using date() object and related functions.

var date = new Date();	
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var fullDate = day + "-" +(month + 1) + "-" + year;



More about date time in JavaScript