[英]DateTime local and utc the same
我從webbrowser發送此字符串"2019-01-25T00:00:00+01:00"
我對此並不理解:這是當地時間,在utc中應為"2019-01-24T23:00:00"
但是在服務器上:
myDate.Kind is local
myDate "2019-01-24T23:00:00"
myDate.ToLocalTime() is the same "2019-01-24T23:00:00"
myDate.ToUniversalTime() is the same "2019-01-24T23:00:00"
我需要的是如果我發送了此字符串"2019-01-25T00:00:00+01:00"
我需要在服務器上知道本地和utc之間存在1h的差異
並由點網核心api自動解析此字符串(DateTime是方法參數)
DateTime
類型沒有任何時區概念:如果需要,請改用DateTimeOffset
。
我懷疑您的服務器位於UTC時區,因為ToLocalTime和ToUniversalTime給出的結果相同。
您可以嘗試AdjustToUniversal
選項,例如
string source = "2019-01-25T00:00:00+01:00";
DateTime myDate = DateTime.ParseExact(
source,
"yyyy-MM-dd'T'HH:mm:sszzz",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
Console.Write(string.Join(Environment.NewLine,
$"Value = {myDate:HH:mm:ss}",
$"Kind = {myDate.Kind}"));
結果:
Value = 23:00:00
Kind = Utc
編輯:如果您無法更改服務器的代碼,因此必須提供一個string
( source
),以使DateTime.Parse(source)
將返回正確的日期,則可以嘗試將現有時區( +01:00
)轉換為祖魯語 :
string source = "2019-01-25T00:00:00+01:00";
// 2019-01-24T23:00:00Z
source = DateTime
.ParseExact(source,
"yyyy-MM-dd'T'HH:mm:sszzz",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal)
.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
然后在服務器上
// source is treated as UTC-time;
// However, by default (when no options provided) myDate will have Kind = Local
DateTime myDate = DateTime.Parse(source);
Console.Write(string.Join(Environment.NewLine,
$"Value = {myDate:HH:mm:ss}",
$"Kind = {myDate.Kind}"));
結果:
Value = 02:00:00 // May vary; adjusted to server's time zone (In my case MSK: +03:00)
Kind = Local // DateTime.Parse returns Local when no options specified
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.