Convert A Date Into Timestamp In JavaScript

27th February 2009

I have previously talked about using PHP to convert from a date to a time, but what about doing the same in JavaScript?

To get the unix timestamp using JavaScript you need to use the getTime() function of the build in Date object. As this returns the number of milliseconds then we must divide the number by 1000 and round it in order to get the timestamp in seconds.

Math.round(new Date().getTime()/1000);

To convert a date into a timestamp we need to use the UTC() function of the Date object. This function takes 3 required parameters and 4 optional parameters. The 3 required parameters are the year, month and day, in that order. The optional 4 parameters are the hours, minutes, seconds and milliseconds of the time, in that order.

To create the time do something like this:

  1. var datum = new Date(Date.UTC('2009','01','13','23','31','30'));
  2. return datum.getTime()/1000;

This prints out 1234567890 as a timestamp. Here is a function to simplify things:

  1. function toTimestamp(year,month,day,hour,minute,second){
  2. var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
  3. return datum.getTime()/1000;
  4. }

Notice that when adding in the month you need to minus the value by 1. This is because the function requires a month value between 0 and 11. However, there is an easier way of getting the timestamp by using the parse() function. This function returns the timestamp in milliseconds, so we need to divide it by 1000 in order to get the timestamp.

  1. function toTimestamp(strDate){
  2. var datum = Date.parse(strDate);
  3. return datum/1000;
  4. }

This can be run by using the following, not that the date must be month/day when writing the date like this.

alert(toTimestamp('02/13/2009 23:31:30'));

Or even this:

alert(toTimestamp('2009 02 13 23:31:30'));

 

Comments

Permalink

Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns.

works perfectly thanks

Ravi (Fri, 10/05/2018 - 07:30)

Permalink

Sweet! Thank you for the information!

Nicephorus Denisov (Fri, 09/27/2019 - 08:53)

Permalink

Nіce! Thanks a lot for the guide!

Joseph Carroll (Sun, 10/06/2019 - 04:55)

Permalink

Thanks :)

rüzgar (Fri, 05/08/2020 - 12:57)

Add new comment

The content of this field is kept private and will not be shown publicly.