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

标签 c# .net datetime timezone

我的意思是将严格的 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/

相关文章:

c# - 从 C# 代码从 SQLite 导入/导出 CSV

c# - 在 4.0 项目中引用 .net Framework 4.5.1 程序集

python - 在python中将字符串解析为时间值

.net - 简单的 .NET XML 库

javascript - Angularjs,如何设置输入的 ng-model 以通过自动绑定(bind)更改日期和时间?

java - picking 12 :00 比较时间不正确

只能在具有另一个属性的类中的方法上的 C# 属性

c# - 在迭代方法调用的结果时,Parallel.Foreach 将如何表现?

c# - MVC 将自定义异常重新抛出为 JSON

c# - 项目 'ClassLibrary1.csproj' 目标 'netstandard2.1' 。它不能被以 '.NETFramework,Version=v4.8' 为目标的项目引用