如何将诸如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"
其他回答
我只是找到了一个优雅的方法:
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"
如果您不确定输入值,也可以如下所示使用DateTime.TryParseExact()。
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
由于您处理的是基于24小时的时间,并且您使用逗号分隔秒分数,因此我建议您指定一个自定义格式:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
我尝试了各种方法。对我有用的是:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
我的数据是2017年9月24日上午9:31:34
使用DateTime.Parse(字符串):
DateTime dateTime = DateTime.Parse(dateTimeStr);
推荐文章
- 返回匿名类型的结果?
- indexOf()和search()的区别是什么?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 我如何在Swift连接字符串?
- 在c#的控制台应用程序中使用'async
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在mongodb中存储日期/时间的最佳方法
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 如何获得一个变量值,如果变量名存储为字符串?
- 用c#解析JSON
- Windows窗体中的标签的换行