문제

Hello is there a way to convert this string "Saturday 04/23/2013 11:05 PM" to a valid DateTime Format?

Because it gives me FormatExceptionError everytime I execute this condition:

String was not recognized as a valid DateTime because the day of week was incorrect.

if(DateTime.Parse("Saturday 04/23/2013 11:05 PM") < DateTime.Today)
{
//code here
}

Is there a solution to this problem?

도움이 되었습니까?

해결책

use DateTime.ParseExact()

string _strdate = "Tuesday 04/23/2013 11:05 PM"; // should be tuesday
DateTime _date = DateTime.ParseExact(_strdate,"dddd MM/dd/yyyy hh:mm tt", 
                                     CultureInfo.InvariantCulture)

enter image description here

다른 팁

If you expect invalid data you should use TryParse or TryParseExact

DateTime myDate;
if(DateTime.TryParse("Saturday 04/23/2013 11:05 PM", out myDate))
{
   if (myDate < DateTime.Today) { //code here }
}
else
{
   //Do something here for invalid data
}

String was not recognized as a valid DateTime because the day of week was incorrect.

04/23/2013 is Tuesday, not Saturday .

Maybe the exception occurs when your datetime statement is Contradiction.

Hope it help...

The date and day of week do not match. 23rd April of 2013 is Tuesday and not Saturday. In no calendar of world you will have this day as Saturday. That's why it gives error String was not recognized as a valid DateTime because the day of week was incorrect.

So may be it converts your date and then validates. Hence it is failing in validation.

But when Tuesday is provided, This will work.

string str = "Tuesday 04/23/2013 11:05 PM";

DateTime dt = DateTime.ParseExact(str, "dddd MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture);

enter image description here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top