How To Convert From Date To Unix_timestamp Using Javascript
Solution 1:
If you are supplying a UTC timestamp and want seconds since 1/1/1970, then:
[...]
Edit
Revisited my original answer and didn't like it, the following is better:
// Given an ISO8601 UTC timestamp, or one formatted per the OP,// return the time in seconds since 1970-01-01T00:00:00ZfunctiontoSecondsSinceEpoch(s) {
s = s.split(/[-A-Z :\.]/i);
var d = newDate(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
returnMath.round(d.getTime()/1000);
}
Note that the string in the OP isn't ISO8601 compliant, but the above will work with it. If the timestamp is in the local timezone, then:
// Given an ISO8601 timestamp in the local timezone, or one formatted per the OP,// return the time in seconds since 1970-01-01T00:00:00ZfunctiontoSecondsSinceEpochLocal(s) {
s = s.split(/[-A-Z :\.]/i);
var d = newDate(s[0],--s[1],s[2],s[3],s[4],s[5]);
returnMath.round(d.getTime()/1000);
}
If decimal seconds should be accommodated, a little more effort is required to convert the decimal part to ms.
Solution 2:
Convert a Unix timestamp to time in JavaScript has solved the problem already...
// create a new javascript Date object based on the timestamp // multiplied by 1000 so that the argument is in milliseconds, not seconds var date = newDate(unix_timestamp*1000);
// hours part from the timestamp var hours = date.getHours();
// minutes part from the timestamp var minutes = date.getMinutes();
// seconds part from the timestamp var seconds = date.getSeconds();
// will display time in 10:30:23 format var formattedTime = hours + ':' + minutes + ':' + seconds;
Solution 3:
Not sure if this will help. But remember you can do this in MySQL using UNIX_TIMESTAMP(DateTime) function. You also have the other way around function that turns unix timestamps into DateTimes: FROM_UNIXTIME(UnixTimestamp).
Hope this helps!
Solution 4:
Have you tried building the date object then using .getTime()? This is probably what you want.
eg: Math.round(new Date('2012-03-19 21:01:54').getTime() / 1000)
Post a Comment for "How To Convert From Date To Unix_timestamp Using Javascript"