简体   繁体   English

DateTime.ParseExact 到 UTC 值

[英]DateTime.ParseExact to UTC value

I retrieve a date and time from my web api and set it as so:我从我的 web api 检索日期和时间并将其设置为:

tmp = DateTime.ParseExact(dateAndTimeFromApi, "dd/MM/yyyy HH:mm:ss", null);

I need to convert this DateTime to a UTC DateTime.我需要将此 DateTime 转换为 UTC DateTime。 When I add.ToUniversalTime() it does not convert from local to UTC.当我 add.ToUniversalTime() 它不会从本地转换为 UTC。 My current timezone is UTC + 2. So I want to get from 11am to 9am after the conversion.我当前的时区是 UTC + 2。所以我想在转换后从上午 11 点到上午 9 点。

How can I do this if I want to keep the "dd/MM/yyyy HH:mm:ss" format?如果我想保持“dd/MM/yyyy HH:mm:ss”格式,我该怎么做?

You should add a couple of DateTimeStyles (in the System.Globalization namespace) flags as the 4th parameter.您应该添加几个 DateTimeStyles(在 System.Globalization 命名空间中)标志作为第四个参数。

By default the resulting DateTime will have an Unsepcified DateTimeKind therefore adjustments between local and UTC will fail.默认情况下,生成的 DateTime 将具有Unsepcified DateTimeKind 因此本地和 UTC 之间的调整将失败。 - DateTimeStyles.AssumeLocal will make sure that DateTimeKind.Local is set. - DateTimeStyles.AssumeLocal将确保 DateTimeKind.Local 已设置。

The DateTimeStyles.AdjustToUniversal flag will also perform the conversion between DateTimeKind.Local and DateTimeKind.UTC DateTimeStyles.AdjustToUniversal标志还将执行 DateTimeKind.Local 和 DateTimeKind.UTC 之间的转换

var tmp = DateTime.ParseExact("28/07/2022 10:51:25", "dd/MM/yyyy HH:mm:ss", null,
    DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM