Monday, July 26, 2010

Converting Local time to Unix Timestamp in Javascript

After some thought, I finally was able to come up with a javascript solution to convert the local time to a Unix timestamp.

Basically I used a few main Javascript functions: getTime(), getTimezoneOffset()

The first function (getTime) will convert the time we get from the Date() function, into a UNIX stamp. Unfortunately, when we convert this string, we won't get the local time, but the main UTC.

This is where I had to use getTimezoneOffset(). This function finds out the difference in minutes between the main UTC and your local time zone. I'm going to use the number I get from getTimezoneOffset and subtract it from the UNIX timestamp number I created. But getTimezoneOffset() is in minutes, so we'll have to convert it to the data type of the UNIX timestamp, which is milliseconds. Thus, we'll have to multiply it by 60,000 (60 seconds in a minute, and 1000 milliseconds in a second).

Below is the code I finally used (put this in a script tag):


var theDate = new Date();
var theTime = theDate.getTime();
var localMil = theDate.getTimezoneOffset()*60*1000;
document.write((theTime-localMil));


No comments:

Post a Comment