簡體   English   中英

使用 JSON.stringify() 和 JSON.parse() 時 Date() 的問題

[英]Issues with Date() when using JSON.stringify() and JSON.parse()

我正在嘗試使用 JavaScript 計算兩次之間的差異。 這只是基本的數學,但我在使用JSON.stringify()JSON.parse()似乎有一些問題。

如果您想知道為什么我將JSON.stringify()函數應用於日期,那是因為我使用本地存儲在客戶端存儲一些數據,並在客戶端再次登陸我的網站時使用它(這樣會更快)而不是向服務器發出更多請求)。 該數據通常會data_update更新一次(我通過 API 從另一個網站獲取數據),因此我設置了一個data_update變量並將其與其他數據存儲在一起。

這樣我從本地存儲中獲取存儲的數據並檢查data_update (這是一個日期/時間)和檢查它的時間/日期之間的差異,看看它是否大於一周/天/等.

這就是我使用 JSON 函數的原因。 我的問題是,當我解析本地存儲中的數據時,日期似乎與Date()對象不同。

我正在嘗試執行下一個操作:

var x = JSON.parse(JSON.stringify(new Date()));

var y = JSON.parse(this.get_local_storage_data(this.data_cache_key)); // the data object stored on local storage

var q = y.data_update; // this is the variable where the Date() was stored

console.log(Math.floor((x-q)/1000));

以上將返回null 此外,當我想查看Math.floor(x)結果時,它再次返回null

那么在這種情況下我能做什么呢? 有沒有解決辦法?

如果您查看日期的 JSON.stringify 輸出,您會看到:

JSON.stringify(new Date())

結果是一個字符串。 JSON 沒有 Date 對象的原始表示,JSON.parse 將自動轉換回 Date 對象。

Date 對象的構造函數可以接受一個日期字符串,因此您可以通過執行以下操作將這些字符串值轉換回日期:

var x = new Date(JSON.parse(JSON.stringify(new Date())));

然后算術將起作用。

x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON.stringify(new Date())

返回

“2013-10-06T15:32:18.605Z”

感謝上帝是: Date.prototype.toISOString()

正如推薦的答案所暗示的那樣,使用JSON.stringify時,日期只是轉換為字符串。

另一種可能適合此用例的方法是使用Date.now()以毫秒為單位存儲時間:

 // Date.now() instead of new Date() const millis = Date.now(); console.log(millis); // same output as input console.log(JSON.parse(JSON.stringify(millis)));

這樣你就可以確保在使用JSON.parse時進入JSON.stringify是一樣的。

如果您有兩個毫秒值,使用<>比較日期也很容易。

另外,您可以隨時將毫秒轉換為日期(通常在將其呈現給用戶之前):

 const millis = Date.now(); console.log(millis); console.log(new Date(millis));

注意:通常不推薦使用毫秒作為日期表示,至少在您的數據庫中不推薦: https : //stackoverflow.com/a/48974248/10551293

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM