問題描述
在編寫 Web 應用程序時,將(服務器端)所有日期時間作為 UTC 時間戳存儲在數據庫中是有意義的.
While writing a web application, it makes sense to store (server side) all datetimes in the DB as UTC timestamps.
當我注意到在 JavaScript 中的時區操作方面,您本身無法做很多事情時,我感到很驚訝.
I was astonished when I noticed that you couldn't natively do much in terms of Timezone manipulation in JavaScript.
我稍微擴展了 Date 對象.這個功能有意義嗎?基本上,每次我向服務器發送任何東西時,它都會是一個用這個函數格式化的時間戳......
I extended the Date object a little. Does this function make sense? Basically, every time I send anything to the server, it's going to be a timestamp formatted with this function...
你能看出這里有什么大問題嗎?還是換個角度的解決方案?
Can you see any major problems here? Or maybe a solution from a different angle?
Date.prototype.getUTCTime = function(){
return new Date(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
).getTime();
}
這對我來說似乎有點令人費解.我也不太確定性能.
It just seems a little convoluted to me. And I am not so sure about performance either.
推薦答案
以這種方式構造的日期使用本地時區,導致構造的日期不正確.設置某個日期對象的時區是從包含時區的日期字符串構造它.(我無法讓它在舊版 Android 瀏覽器中運行.)
Dates constructed that way use the local timezone, making the constructed date incorrect. To set the timezone of a certain date object is to construct it from a date string that includes the timezone. (I had problems getting that to work in an older Android browser.)
請注意,getTime()
返回毫秒,而不是普通秒.
Note that getTime()
returns milliseconds, not plain seconds.
對于 UTC/Unix 時間戳,以下內容就足夠了:
For a UTC/Unix timestamp, the following should suffice:
Math.floor((new Date()).getTime() / 1000)
它會將當前時區偏移量計入結果中.對于字符串表示,David Ellis' 答案有效.
It will factor the current timezone offset into the result. For a string representation, David Ellis' answer works.
澄清一下:
new Date(Y, M, D, h, m, s)
該輸入被視為當地時間.如果傳入UTC時間,結果會有所不同.觀察(我現在在 GMT +02:00,現在是 07:50):
That input is treated as local time. If UTC time is passed in, the results will differ. Observe (I'm in GMT +02:00 right now, and it's 07:50):
> var d1 = new Date();
> d1.toUTCString();
"Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time
> Math.floor(d1.getTime()/ 1000)
1332049834
> var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() );
> d2.toUTCString();
"Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!
> Math.floor(d2.getTime()/ 1000)
1332042634
另請注意,getUTCDate()
不能替代 getUTCDay()
.這是因為 getUTCDate()
返回 一個月中的哪一天;而 getUTCDay()
返回 星期幾.
Also note that getUTCDate()
cannot be substituted for getUTCDay()
. This is because getUTCDate()
returns the day of the month; whereas, getUTCDay()
returns the day of the week.
這篇關于如何在 JavaScript 中獲取 UTC 時間戳?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!