我有这种文字格式:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
Run Code Online (Sandbox Code Playgroud)
我需要得到这个:dd/mm/yyyy
怎么用C#Winform代码呢?
提前致谢
您可以使用DateTime.Parse(...)解析它,然后使用DateTime.ToString()将其打印出来.
var date1 = DateTime.Parse("8/27/2009 8:23:06 AM", CultureInfo.GetCultureInfo("en-US"));
var date2 = DateTime.Parse("Thu Aug 27 2009 12:42:22", CultureInfo.GetCultureInfo("en-US")); //Edited the date a little
var date3 = DateTime.Parse("08/12/2009 20:22", CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(date1.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date2.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date3.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Run Code Online (Sandbox Code Playgroud)
其中一些对你来说可能是多余的.我住在DK并拥有DK文化,所以如果你有一台美国电脑,我就无法解析相同的字符串.因此,我明确地设定了文化.如果您有标准的美国文化或想要将应用程序适应其他文化,那么您可以使用:
//for parsing
var date1 = DateTime.Parse("A date");
//for printing
date1.ToShortDateString();
Run Code Online (Sandbox Code Playgroud)
作为fletcher,如果您解析用户输入或数据,您可以使用DateTime.TryParse来预期提供日期字符串中的缺陷.