Javascript: how to calculate the beginning of a day with milliseconds?
I agree with Thilo (localized to time zone), but I'd probably tackle it like this:
// Original: Thu Jun 21 2012 19:58:20 GMT-0400 (Eastern Daylight Time)
var ms = 1340323100024;
var msPerDay = 86400 * 1000;
var beginning = ms - (ms % msPerDay);
// Result: Wed Jun 20 2012 20:00:00 GMT-0400 (Eastern Daylight Time)
Or, if you prefer:
Number.prototype.StartOfDayMilliseconds = function(){
return this - (this % (86400 * 1000));
}
var ms = 1340323100024;
alert(ms.StartOfDayMilliseconds());
EDIT
If you're particular about the timezone, you can use:
// Original: Thu Jun 21 2012 19:58:20 GMT-0400 (Eastern Daylight Time)
var ms = 1340323100024;
var msPerDay = 86400 * 1000;
var beginning = ms - (ms % msPerDay);
beginning += ((new Date).getTimezoneOffset() * 60 * 1000);
// Result: Thu Jun 21 2012 00:00:00 GMT-0400 (Eastern Daylight Time)
Notice that the offset is now removed so the 8pm the previous day turns in to midnight of the actual day on the timestamp. You can also probably (depending on implementation) do the addition before or after you modulo for the beginning of the day--your preference.