C#字符串转DateTime
将⽂本正确转换为需要执⾏三个⼦任务:1、正确格式的⽇期和时间字符串。2、区域性,不同地区的⽇期和时间表⽰格式有区别,字符串格式有区别。3、指定转换格式,例如转换后的DateTime,可能没有时间部分。
使⽤Parse转换和TryParse转换:
string dateInput = "Jan 1, 2009";
DateTime parsedDate = DateTime.Parse(dateInput);
Console.WriteLine($"默认区域{CultureInfo.CurrentCulture.Name}:"+parsedDate);
// 说明字符串格式是en-us区域
DateTime parsedDate1 = DateTime.Parse(dateInput,new CultureInfo("en-us"));
Console.WriteLine("使⽤en-us:" + parsedDate1);
// name不区分⼤⼩写
// public CultureInfo(string name);
CultureInfo MyCultureInfo = new CultureInfo("de-DE");
string MyString = "12 Juni 2008";
DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo);
Console.WriteLine(MyDateTime);
DateTime dateTime;
DateTime.TryParse("Jan 1, 2009",new CultureInfo("en-us"),DateTimeStyles.None,out dateTime);
ParseExact:可以定义字符串转换格式,可以是中的⼀种,也可以是,但未必都能转换成功。CultureInfo.InvariantCulture了解:
       string dateString, format;
DateTime result;
var provider = new CultureInfo("fr-FR");
string转date的方法dateString = "18/08/2015 06:30:15.006542";
// ⾃定义格式
format = "dd/MM/yyyy HH:mm:ss.ffffff";
try
{
result = DateTime.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);
}
// Parse date-only value with invariant culture.
provider = CultureInfo.InvariantCulture;
dateString = "06/15/2008";     
format = "d";
try
{
result = DateTime.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);
}
查看有哪些CultureInfo。CultureInfo.GetCultures(CultureTypes.AllCultures)。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。