Javascript: how to calculate the beginning of a day with milliseconds?

泄露秘密 提交于 2019-12-23 12:18:08

问题


i want to figure out the time from the beginning of the day given a days milliseconds.

so say i'm given this: 1340323100024 which is like mid day of 6/21/2012. now i want the milliseconds from the beginning of the day, which would be 1340262000000 (at least i think that's what it's supposed to be.)

how do i get 1340262000000 from 1340323100024?

i tried doing

Math.floor(1340323100024/86400000) * 86400000 

but that gives me 1340236800000, which if i create a date object out of it, says its the 20th.

i know i can create a date object from 1340323100024, then get the month, year, and date, to create a new object which would give me 1340262000000, but i find it ridiculous i can't figure out something so simple.

any help would be appreciated.

btw, i'm doing this in javascript if it makes any difference.


回答1:


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.




回答2:


Actually, it should be (currTimeMilli - 18000000) % 864000000 to get the number of milliseconds since the beginning of the day for GMT+5.



来源:https://stackoverflow.com/questions/11149555/javascript-how-to-calculate-the-beginning-of-a-day-with-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!