昨天,今天,明天,每天的每天,你是否都多懂得一点点...

星期五, 三月 15, 2019

How to get UTC 0 o'clock of current date in javascript

It's common that we need to get the UTC date of today. With Javascript, you can get the current day easily with new Date() or Date.now(). 

But sometimes, we would like to treat any time in the same day the same way, which means we don't want to know the hour, minute, second of the day. We just care about the day. 

You can always convert the date to string and ignore the hours etc. which is inefficient. It's also problematical if we need to save the date into db. So convert to string then convert back to time stamp is necessary but make it more inefficient.

Today I am showing a pure mathematical way.

TodayUTCZeroOClock = Now - Now%DayInMiniSeconds

Example:

a = Date.now()
1552561275091
day = 1000 * 60 * 60 * 24
86400000
a%day
39675091
b = a - a%day
1552521600000
new Date(b)
Thu Mar 14 2019 13:00:00 GMT+1300 (New Zealand Daylight Time)

Note that 13 O'clock is UTC 0 0'clock

没有评论:

其它博客地址

此博客的同步博客地址: http://fengnz.wordpress.com
这里进入我的MSN SPACE.