當我檢查 optionDate 的 DateTime 屬性的 DateTimeKind 值時,我看到未指定,即使我在下面的代碼中將 dt 的 DateTimeKind 設定為 Utc。我希望 optionDate 有一個 DateTime,它的 DateTimeKind 屬性設定為 Utc。我哪里錯了?
var dt = new DateTime(Convert.ToInt32(optionDateInfo.dateTime.year),
Convert.ToInt32(optionDateInfo.dateTime.month), Convert.ToInt32(optionDateInfo.dateTime.day),
Convert.ToInt32(optionDateInfo.dateTime.hour), Convert.ToInt32(optionDateInfo.dateTime.minutes),
0, DateTimeKind.Utc);
var optionDate = new DateTimeOffset(dt);
uj5u.com熱心網友回復:
這是記錄在案的:
DateTimeOffset.DateTime
回傳的 DateTime 物件的 DateTime.Kind 屬性的值為 DateTimeKind.Unspecified。
請注意, aDateTimeOffset沒有“種類”。它具有日期、時間和偏移量。當您將DateTimewith kind傳遞Utc給它時,它會將其偏移量設定為 0,并將其日期和時間設定為DateTime給定的。在這一點上,你DateTimeKind“迷失了”。
偏移量為 0 并不一定意味著它的種類是DateTimeKind.Utc。它可能是倫敦的當地時間,也可能是非洲的某個地方。所以它也不能僅僅因為它的偏移量是 0就給你一個DateTimewith kind Utc。
另外,DateTime能夠表示3種東西已經是一個有問題的設計,如果DateTime現在屬性可以DateTime根據offset是否匹配本地時間,是UTC,還是其他東西來回傳3種不同的,那就更糟了。
相反,它被設計為具有 3 個屬性,為您DateTime提供不同種類的 s。
DateTime給你的日期和時間部分DateTimeOffset,以實物UnspecifiedLocalDateTime將 的日期和時間部分轉換為DateTimeOffset當前時區,并為您提供一個DateTimewith kindLocal。UtcDateTime將 的日期和時間部分轉換DateTimeOffset為 UTC,并為您提供一個DateTimewith kindUtc。
如果你想要一個DateTimewith kind Utc,你應該使用最后一個。
uj5u.com熱心網友回復:
使用指定種類
var myUtcZeroOffset = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc)
//If constructing a datetime offset to be not utc you can supply the offset instead
var myOffSetExplicitLocal = new DateTimeOffset(DateTime.Now, new TimeSpan(1, 0, 0));
var localDateTime = myOffSetExplicitLocal.DateTime;
var utcZeroOffSetDateTime = myOffSetExplicitLocal.UtcDateTime;
更糟糕的是,這是微軟的一個批評實施,因為通用協調時間不是一個時區而是一個符號,根據 ISO 8601,所以實際上 toUTC 作為一個概念是有缺陷的,因為 '2021-11-02T10:16: 25.12345 01:00' 在 UTC 格式和 UTC 零偏移量中完全有效,俗稱 Zulu 是 '2021-11-02T09:16:25.12345Z' 等價物,然后獲得 datetimekind UTC 實際上只是在協調時間零線在 GMT 緯度附近,但使它協調的是 00:00 中的 部分可以縮寫為 Z,因此做了很多作業來減輕固有的沖突,并且與構建服務器和云提供商的 .Local 尤其可疑,所以我建議始終堅持使用 ISO 8601 字串,除非你真的需要在你的資料庫中使用它們進行日期操作,在這種情況下,命名適當的欄位,如 DateTimeCreatedUtcZero 列,例如我對這個主題的五美分理由,希望它有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344866.html
