C# 字符串转DateTime

将文本正确转换为 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了解:https://www.cnblogs.com/GreenLeaves/p/6757917.html

       string dateString, format;
            DateTime result;
            var provider = new CultureInfo("fr-FR");
            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)。

posted @ 2020-04-04 11:58  舒碧  阅读(6741)  评论(0编辑  收藏  举报