简体   繁体   English

C#DateTime.ToString“o”格式在Azure上返回不同的字符串

[英]C# DateTime.ToString “o” Format Returns Different String on Azure

I have a scenario in which I want to turn UTC dates into ISO 8601 strings with a certain timezone to send down via web api. 我有一个场景,我希望将UTC日期转换为具有特定时区的ISO 8601字符串,以通过web api向下发送。 The recommended way to do this is to use TimeZoneInfo like so: 建议的方法是使用TimeZoneInfo,如下所示:

var configuredTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneString);
var localTime = DateTime.SpecifyKind(TimeZoneInfo.ConvertTimeFromUtc(utcTime, configuredTimeZone), DateTimeKind.Local);
var stringResult = localTime.ToString("o");

This works fine on my local machine, but I'm running into a very weird situation where ToString outputs a different string when the code is hosted in an Azure web app. 这在我的本地机器上工作正常,但我遇到了一个非常奇怪的情况,当代码托管在Azure Web应用程序中时,ToString输出不同的字符串。 Locally I get 2017-02-20T00:00:00-06:00 (which is what I want, as it contains the timezone info I need), but when hosted in Azure I get 2017-02-20T00:00:00+00:00.(which is in UTC, not what I want). 本地我得到2017-02-20T00:00:00-06:00(这是我想要的,因为它包含我需要的时区信息),但是当在Azure中托管时,我得到2017-02-20T00:00:00+ 00:00。(这是UTC,不是我想要的)。 Since I am manually applying the time zone I want, I am not sure why the format is appending the wrong timezone information. 由于我手动应用我想要的时区,我不确定为什么格式附加了错误的时区信息。 Has anyone run into this before? 有没有人遇到过这个?

As has been mentioned in the comments, System.DateTime cannot store time zones. 正如评论中提到的, System.DateTime无法存储时区。 All it knows is "local" or "UTC". 它所知道的只是“本地”或“UTC”。 Being hosted in Azure, its "local" time is UTC. 在Azure中托管,其“本地”时间 UTC。

So your statement of TimeZoneInfo.ConvertTimeFromUtc(utcTime, configuredTimeZone) would convert the UTC time to your time (midnight of the 20th), but because DateTime holds no timezone, it is of DateTimeKind.Unspecified . 因此,您的TimeZoneInfo.ConvertTimeFromUtc(utcTime, configuredTimeZone)语句会将UTC时间转换为您的时间(20日午夜),但由于DateTime没有时区,因此它是DateTimeKind.Unspecified Your DateTime.SpecifyKind(..., DateTimeKind.Local) simply tells it that it is of type "local", and in the case of an Azure host, UTC+00:00. 您的DateTime.SpecifyKind(..., DateTimeKind.Local)只是告诉它它是“本地”类型,如果是Azure主机,则为UTC + 00:00。

If timezones are important, you want to utilise System.DateTimeOffset instead of DateTime . 如果时区很重要,则需要使用System.DateTimeOffset而不是DateTime It is specifically built for holding and manipulating (as its name implies) timezone offsets. 它专门用于保持和操纵(顾名思义)时区偏移。

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

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