从字符串c#转换为戳时间格式
本文关键字:时间 格式 转换 字符串 | 更新日期: 2023-09-27 17:50:59
我使用javascript选择一个日期并显示格式为(11-05-2015 17:37)
,我试着解析它到日期时间,如下面的代码
DateTime taskDate = Convert.ToDateTime(txtDate.Text);
并保存到我的日期库中,如
TO_DATE('" + createOn + "')
给我一个错误调用"String was not recognized as a valid DateTime "
谁有其他的方法来解析它到stamptime ?
txtDate。文本值为27-05-2015 09:37
Convert.ToDateTime
在从字符串转换为日期时间时使用当前的线程文化格式。
如果要转换的字符串有另一种格式,则需要使用DateTime.ParseExact
并显式提供适当的格式。
例如,在你的例子中,它应该是
DateTime taskDate = DateTime.ParseExact("11-05-2015 17:37", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
还可以查看自定义日期时间格式字符串以供参考。
可以使用DateTime。ParseExact或DateTime。TryParseExact
检查下面的代码:
DateTime taskDate = DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture);
或
DateTime taskDate;
if (DateTime.TryParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out taskDate))
{
//code if date valid
}
else
{
//code if date invalid
}