[英]C# DateTimeOffset to DateTime Conversion
有人可以向我解釋為什么以下代碼返回 DateTimeKind.Unspecified。 我期待 DateTimeKind.Utc:
DateTimeOffset dateTimeOffset = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
DateTimeKind dateTimeKind = dateTimeOffset.DateTime.Kind;
從DateTime
到DateTimeOffset
隱式轉換運算符的行為與DateTimeOffset
構造函數相同。 您可以查看來源以了解詳細信息
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc) {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
並且ValidateDate()
返回Unspecified
kind
...
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
這里的重點也在DateTimeOffset
構造函數的備注部分中描述
此構造函數的行為取決於
dateTime
參數的 DateTime.Kind 屬性的值:如果
DateTime.Kind
值為DateTimeKind.Utc
,則新實例的DateTime
屬性設置為 dateTime,Offset
屬性設置為零。如果
DateTime.Kind
值為DateTimeKind.Local
或DateTimeKind.Unspecified
,則新實例的DateTime
屬性設置為等於 dateTime,Offset
屬性設置為等於本地系統當前時區的偏移量。
您正在檢查輸入日期時間Kind
並根據它提取Offset
值。 結果DateTimeOffset
的DateTime
屬性是Unspecified
,因為Offset
屬性已經表示日期偏移量。 DateTime
的屬性DateTimeOffset
也說,
返回的
DateTime
對象的DateTime.Kind
屬性的值為DateTimeKind.Unspecified
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.