我正在从网络浏览器发送此字符串"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(日期时间是方法参数)自动完成解析此字符串
答案 0 :(得分:1)
DateTime
类型没有任何时区概念:如果需要,请改用DateTimeOffset
。
我怀疑您的服务器位于UTC时区,因为ToLocalTime和ToUniversalTime给出的结果相同。
答案 1 :(得分:1)
您可以尝试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
)转换为 Zulu :
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