简体   繁体   English

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

[英]Format String to Datetime with Timezone

I have a string s = "May 16, 2010 7:20:12 AM CDT that 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 object。在下面的代码中,我在尝试解析具有已知的文本时收到日期格式无法转换错误格式。

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 的形式出现......我认为是什么导致了问题或我的格式?

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.IsDaylightSavingTime and TimeZone.CurrentTimeZone 对于夏令时,请考虑DateTime.IsDaylightSavingTimeTimeZone.CurrentTimeZone

Custom Date and Time Format Strings 自定义日期和时间格式字符串

Make sure the DateTime is unambiguously DateTimeKind.Utc. 确保DateTime是明确的DateTimeKind.Utc。 Avoid "GMT", it is ambiguous for daylight saving. 避免使用“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 GMT-06:00

For more detail refer this Link 有关详细信息,请参阅此链接

I convert my date string with timezone "Thu, 22 Sep 2022 06:38:58 +0200" using "ddd, dd MMM yyyy HH:mm:ss zzz":我使用“ddd, dd MMM yyyy HH:mm:ss zzz”将我的日期字符串与时区“Thu, 22 Sep 2022 06:38:58 +0200”转换:

var dateString = "Thu, 22 Sep 2022 06:38:58 +0200";
string[] acceptedDateFormats = { "ddd, dd MMM yyyy HH:mm:ss zzz" };

var dateParsed = DateTime.TryParseExact(dateString, acceptedDateFormats,
  CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);

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

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