gpt4 book ai didi

c# - 如何设置 DateTime 值的时区(或种类)?

转载 作者:IT王子 更新时间:2023-10-29 03:59:41 26 4
gpt4 key购买 nike

我的意思是将严格的 UTC 时间存储在 DateTime 变量中并以 ISO 8601 格式输出。

最后我使用了 .ToString("yyyy-MM-ddTHH:mm:sszzz"),它发现时区是 UTC+01:00。

我试过使用 .Kind = DateTimeKind.Utc,但它说 Kind 属性没有 setter。

如何明确指定 UTC 时间? Kind属性是怎么设置的?

最佳答案

如果您想利用本地机器时区,您可以使用 myDateTime.ToUniversalTime() 从您的本地时间或 myDateTime.ToLocalTime() 获取 UTC 时间> 将 UTC 时间转换为本地机器时间。

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

如果您需要将时间从/转换到其他时区,您可以使用 TimeZoneInfo.ConvertTime()TimeZoneInfo.ConvertTimeFromUtc()

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);

List of available timezones

TimeZoneInfo class on MSDN

关于c# - 如何设置 DateTime 值的时区(或种类)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com