如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?
当前回答
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
这个给了你
2019-08-17 11:14:49.000
其他回答
转换。ToDateTime或DateTime。解析
使用DateTime.Parse(字符串):
DateTime dateTime = DateTime.Parse(dateTimeStr);
试试下面的方法,strDate是你的日期,格式为'MM/dd/yyyy'
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
如果您不确定输入值,也可以如下所示使用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
}
你想快点吗?
假设您有一个格式为yyMMdd的日期。
我发现转换它的最快方法是:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
只需根据您选择的日期格式选择索引。如果你需要速度,你可能不介意函数的“非泛型”方式。
此方法所需时间约为以下操作所需时间的10%:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- Printf与std::字符串?
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 不区分大小写的“in”
- 自动化invokerrequired代码模式
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?