字符串未被识别为有效的DateTime [英] string was not recognized as valid DateTime
本文介绍了字符串未被识别为有效的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字符串未被识别为有效日期时间
和我的日期字符串是27/04/2014 00:00:00 AM
我不知道为什么我收到此错误
objrpt.ToDate = Convert.ToDateTime(txttodate.Text);
例外情况不是来自db
string was not recognized as valid DateTime
and my date string is 27/04/2014 00:00:00 A.M.
I don't know Why I'm getting this error
objrpt.ToDate = Convert.ToDateTime(txttodate.Text);
exception raising fro here not from db
推荐答案
1。您必须使用TryParse方法检查日期时间字符串是否有效;
2.如果它是有效的日期时间字符串,则转换为datetime,否则中止。
1. You have to check that the datetime string is a valid one using TryParse method;
2. If it is a valid datetime string, then do the conversion to datetime else abort.
using System;
public class Program
{
public static void Main()
{
string dateString = "27/04/2014 00:00:00 AM";
Console.WriteLine("The original string is {0}", dateString);
DateTime dt;
if (DateTime.TryParse(dateString, out dt))
{
string format = "yyyy-MM-dd";
// do something with dt
Console.WriteLine(dt.ToString(format));
}
else
{
Console.WriteLine("Not a valid datetime");
}
}
}
It's getting error for datetime format because your string is in "dd/MM/yyyy" format
It will unable to convert datetime it needs like "MM/dd/yyyy" or "yyyy/MM/dd"
Hope so
Then you need to changes your string date="04/27/2014" like this
试试这个
string CrDate = Convert.ToDateTime(Your field)。ToString();
try this
string CrDate = Convert.ToDateTime("Your field").ToString();
这篇关于字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文