如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?
当前回答
我只是找到了一个优雅的方法:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
其他回答
试试下面的方法,strDate是你的日期,格式为'MM/dd/yyyy'
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
使用DateTime.Parse(字符串):
DateTime dateTime = DateTime.Parse(dateTimeStr);
我尝试了各种方法。对我有用的是:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
我的数据是2017年9月24日上午9:31:34
我只是找到了一个优雅的方法:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
世界上不同的文化以不同的方式书写日期字符串。例如,在美国01/20/2008就是2008年1月20日。在法国,这将抛出InvalidFormatException异常。这是因为法国的日期时间是日/月/年,而美国的日期时间是月/日/年。
因此,像20/01/2008这样的字符串在法国将解析到2008年1月20日,然后在美国抛出InvalidFormatException。
要确定当前区域性设置,可以使用System.Globalization.CultureInfo.CurrentCulture。
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- Printf与std::字符串?
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 不区分大小写的“in”
- 自动化invokerrequired代码模式
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?