简体   繁体   English

将日期时间转换为 ToString() 的特定时区

[英]Convert DateTime to specific timezone for ToString()

When writing DateTime values to a text file, I have to make sure the used timezone is always UTC +01:00.DateTime值写入文本文件时,我必须确保使用的时区始终为 UTC +01:00。 The format is then yyyy-MM-ddTHH:mm:sszzz , with the zzz part always equaling +01:00 .格式为yyyy-MM-ddTHH:mm:sszzz ,其中zzz部分始终等于+01:00 This means that, in case the DateTime value is not in UTC +01:00, a conversion needs to happen before writing the output.这意味着,如果 DateTime 值不是 UTC +01:00,则需要在写入输出之前进行转换。

What would be the best way to go about this?解决这个问题的最佳方法是什么?

From the documentation :文档

With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes.对于DateTime值,“zzz”自定义格式说明符表示本地操作系统时区与 UTC 的有符号偏移量,以小时和分钟为单位。 It does not reflect the value of an instance's System.DateTime.Kind property.它不反映实例的System.DateTime.Kind属性的值。 For this reason, the "zzz" format specifier is not recommended for use with DateTime values.因此,不建议将“zzz”格式说明符用于DateTime值。

Instead, either use DateTimeOffset values (in which "zzz" does what you think it should), or if you continue to use DateTime values then use the "K" specifier .相反,要么使用DateTimeOffset值(其中 "zzz" 执行您认为应该执行的操作),或者如果您继续使用DateTime值,则使用"K" 说明符

For example, on my computer (which is in the US Pacific time zone):例如,在我的计算机上(位于美国太平洋时区):

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz")          // "2017-06-21T14:57:17-07:00"
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssK")            // "2017-06-21T14:57:17Z"
DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz")    // "2017-06-21T14:57:17+00:00"
  • On line 1, even though the time is the UTC time, the offset is incorrectly showing local time.在第 1 行,即使时间是 UTC 时间,偏移量也错误地显示了本地时间。
  • On line 2, the K specifier picks up on the UTC kind and properly gives a Z in the result.在第 2 行, K说明符选择 UTC 类型并在结果中正确给出Z
  • On line 3, the zero offset is properly conveyed by the zzz specifier.在第 3 行,零偏移量由zzz说明符正确传达。

Related: https://stackoverflow.com/a/31223893/634824相关: https : //stackoverflow.com/a/31223893/634824

Using:使用:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz") 

Will result in an error.会导致错误。 Please try this instead:请试试这个:

DateTime.**Now**.ToString("yyyy-MM-ddTHH:mm:sszzz") 

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

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