C#DateTime转换或解析特定格式?
我正在尝试将以下字符串转换为c#中的日期时间值: 2012年3月1日 但是我在调用Convert.ToDateTime或DateTime.Parse时一直遇到这个错误 字符串未被识别为有效的日期时间 我认为需要使用自定义日期格式,但我不知道该格式是什么 如何将上述格式的字符串转换为日期时间值?这对我很有用C#DateTime转换或解析特定格式?,c#,C#,我正在尝试将以下字符串转换为c#中的日期时间值: 2012年3月1日 但是我在调用Convert.ToDateTime或DateTime.Parse时一直遇到这个错误 字符串未被识别为有效的日期时间 我认为需要使用自定义日期格式,但我不知道该格式是什么 如何将上述格式的字符串转换为日期时间值?这对我很有用 DateTime.ParseExact(yourString, "d MMMM yyyy", new CultureInfo("en-US")) string s = "1 Mar
DateTime.ParseExact(yourString, "d MMMM yyyy", new CultureInfo("en-US"))
string s = "1 March 2012";
DateTime dateTime = DateTime.Parse(s);
通过从当前线程获取cultureinfo,可以找到支持的日期时间模式
static void Main(string[] args)
{
const string date = "1 03 2012";
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
Console.WriteLine(DateTime.Parse(date));
Console.WriteLine(Convert.ToDateTime(date));
Console.ReadLine();
}
+1尽管我认为答案需要的内容不仅仅是代码。@JoeTuskan-有总比没有好:D@phoog-我知道这是一个相当简单的问题,只需要一行代码来回答,但即使是文档链接也会有所帮助。否则,这个答案只对那些试图解析完全相同的日期时间格式的人有用。我以为我们在这里试图提供具有持久影响的答案。…。@M.Babcock,我同意你的看法。要么是这样的答案,要么是以重复的形式结束问题。一个好的、详细的答案可能不值得为一个经常出现的问题付出努力。