C# 使用时区将字符串格式化为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11873179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:35:58  来源:igfitidea点击:

Format String to Datetime with Timezone

c#.netparsingtimezone

提问by Warz

I have a string s = "May 16, 2010 7:20:12 AM CDTthat i want to convert into a DateTime object. In the code below i get a Date format cannot be converted error when attempting to parse the text with a known format.

我有一个string s = "May 16, 2010 7:20:12 AM CDT要转换为 DateTime 对象的对象。在下面的代码中,当我尝试用已知格式解析文本时,我得到一个日期格式无法转换错误。

timeStamp = matches[0].Groups[1].Value;
dt = DateTime.ParseExact(timeStamp, "MMM dd, yyyy H:mm:ss tt", null);

The timezone comes in as CDT UTC... and i think is whats causing the problem or my format?

时区以 CDT UTC 的形式出现……我认为是什么导致了问题或我的格式?

采纳答案by rumburak

Central Daylight Time

中部夏令时

Try this:

尝试这个:

string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt = 
    DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "MMM dd, yyyy H:mm:ss tt zzz", null);

EDIT:

编辑:

For daylight savings time please consider DateTime.IsDaylightSavingTimeand TimeZone.CurrentTimeZone

对于夏令时,请考虑DateTime.IsDaylightSavingTimeTimeZone.CurrentTimeZone

Custom Date and Time Format Strings

自定义日期和时间格式字符串

回答by rumburak

Make sure the DateTime is unambiguously DateTimeKind.Utc. Avoid "GMT", it is ambiguous for daylight saving.

确保 DateTime 是明确的 DateTimeKind.Utc。避免使用“GMT”,夏令时含糊不清。

    var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
    string s = dt.ToLocalTime().ToString("MMM dd, yyyy HH:mm:ss tt \"GMT\"zzz");

it's gives output : Dec 31, 2010 19:01:01 pm GMT-06:00

它给出了输出:2010 年 12 月 31 日 19:01:01 pm GMT-06:00

For more detail refer this Link

有关更多详细信息,请参阅此链接