[英]Parse datetime string in Angular
我構建了一個 Golang 服務器,它讀取 SQL 服務器中的 DateTime 字段,它返回給我這種日期:“2020-05-28T11:14:26.227Z”,但是當我嘗試在 TypeScript\Angular 中解析時,它返回給我:“ 28-05-2020 13 :14:26:227" 看起來增加了 2 小時。
也許是錯誤的時區? 如何設置正確的時區?
數據庫和 angular 應用程序都在我的電腦中(同一時區)
在服務器和 JavaScript 之間共享 DateTime 是正確的 PITA。 我想忽略時區,並且覺得不需要整個庫,例如 Moment,所以我為 Angular 編寫了一個轉換助手,如下所示:
在 JavaScript 中轉換從服務器接收的日期:
// Reverse the timezone offset (this might only work for timezones earlier than GMT - so test)
this.translateToClient = function (input) {
if (!input) return null;
let result = new Date(Date.parse(input));
result.setMinutes(result.getMinutes() + result.getTimezoneOffset());
return result;
};
轉換 JavaScript 中的日期以發送回服務器:
// Send back UTC time instead of timezone time.
this.translateToServer = function (input) {
if (!input) return null;
return new Date(Date.UTC(
input.getFullYear()
, input.getMonth()
, input.getDate()
, input.getHours()
, input.getMinutes()
, input.getSeconds()
, input.getMilliseconds()
));
};
注意:一些服務器技術(例如 ASP.NET)也可以自動應用時區偏移,這也必須正確配置。
我發現我需要像這樣將我的 DateTime 發送給客戶端:
DateTime.SpecifyKind(MyValue, DateTimeKind.Utc);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.