如何将字符串转换为日期时间
string value = "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)"
我需要转换为日期时间
我尝试过:
DateTime datetime = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm", null);
要么
DateTime datetime2 = Convert.ToDateTime(value);
例外:字符串未被识别为有效的DateTime。
您的字符串与您的格式不符。
在尝试转换之前,您需要稍微解析该字符串。 例如,可以解析“Apr 28 2012 11:00:00”。 但是,你需要自己转换其余部分。
您可能希望使用此处记录的 DateTimeOffset
,因为它可以保留相对于UTC的时间,就像您的字符串一样。
发现这是文档,非常接近你所拥有的
// Parse date and time with custom specifier. dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; format = "ddd dd MMM yyyy h:mm tt zzz"; try { result = DateTimeOffset.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); }
您指定的格式为“MM / dd / yyyy hh:mm”,但您的字符串甚至不是那种格式。
我怀疑你会遇到“GMT-0400(东部夏令时间)”部分的问题 – 其余部分的格式为“ddd MMM dd yyyy HH:mm:ss”或“ddd MMM d yyyy HH:mm:ss “如果每月的数字不总是两位数。
我建议你分别解析UTC的偏移量,并创建一个DateTimeOffset
– 将第一部分(在GMT之前)解析为未指定的 DateTime
– 然后解析偏移量。 编辑:您可以使用TimeSpan.ParseExact
解析偏移量但是您需要自己处理标志,我相信 – 我看不出任何记录方式解析负面时间跨度:(
编辑:请注意,我的Noda Time项目将允许您解析偏移部分,例如使用“’GMT’+ HHmm”的模式 – 显然我们应对LocalDateTime
部分 – 但您仍然需要分离字符串的不同部分彼此相对。 示例代码:
using System; using System.Linq; using System.Xml.Linq; using NodaTime; using NodaTime.Text; public class Test { static void Main() { string text = "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)"; ZonedDateTime parsed = Parse(text); Console.WriteLine(parsed); } static readonly LocalDateTimePattern LocalPattern = LocalDateTimePattern.CreateWithInvariantInfo("ddd MMM d yyyy HH:mm:ss"); // Note: Includes space before GMT for convenience later static readonly OffsetPattern OffsetPattern = OffsetPattern.CreateWithInvariantInfo("' GMT'+HHmm"); static ZonedDateTime Parse(string text) { int gmtIndex = text.IndexOf(" GMT"); int zoneIndex = text.IndexOf(" ("); // TODO: Validation that these aren't -1 :) string localText = text.Substring(0, gmtIndex); string offsetText = text.Substring(gmtIndex, zoneIndex - gmtIndex); var localResult = LocalPattern.Parse(localText); var offsetResult = OffsetPattern.Parse(offsetText); // TODO: Validate that both are successful var fixedZone = DateTimeZone.ForOffset(offsetResult.Value); return localResult.Value.InZoneStrictly(fixedZone); } }
请注意,这将在固定时区提供ZonedDateTime
– 而不是真正的东部时间。 目前Noda Time没有OffsetDateTime
,这在这里很自然…
请尝试以下方法:
Convert.ToDateTime("Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)".Substring(4, 20))
尝试ddd MMM d yyyy hh:mm:ss zzz
如果它不起作用试试这个
如果您查看自定义日期和时间格式字符串 ,您所拥有的只是此格式的变体:
"ddd MMM dd yyyy h:mm:ss zzz"
只有一些额外的部分:
"ddd MMM dd yyyy h:mm:ss GMTzzz (blah blah blah)"
如果你处理那些,你应该没事:
上述就是C#学习教程:如何将字符串转换为日期时间分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
value = value.Remove(value.IndexOf(" (")); DateTime datetime = DateTime.ParseExact(value, "ddd MMM dd yyyy hh:mm:ss "GMT"zzz", null);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/962309.html