I have a time string in the following format YYYY-MM-DD hh:mm:ss
.
I would like to convert it to the equivalent of passing the date-string into the mysql unix_timestamp function using Javascript.
I tried parsing the date and passing it into the Date.UTC()
function but it seems to be giving me different times then what I want. help.
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:00Z
function toSecondsSinceEpoch(s) {
s = s.split(/[-A-Z :\.]/i);
var d = new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
return Math.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:00Z
function toSecondsSinceEpochLocal(s) {
s = s.split(/[-A-Z :\.]/i);
var d = new Date(s[0],--s[1],s[2],s[3],s[4],s[5]);
return Math.round(d.getTime()/1000);
}
If decimal seconds should be accommodated, a little more effort is required to convert the decimal part to ms.
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 = new Date(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;
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!
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)