Convert A Date Into Timestamp In JavaScript

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:

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

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

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

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.

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

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

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

Permalink

Sweet! Thank you for the information!

Permalink

Nіce! Thanks a lot for the guide!

Permalink

Thanks :)

Permalink

it helped me a lot, very thanks...

Permalink

very nice blog

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.