Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String was not recognized as a valid DateTime

Tags:

c#

c#-4.0

I'm receiving this error "String was not recognized as a valid DateTime" with the code below:

DateTimeOffSet dt=new DateTimeOffset(Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy hh:mm tt")));

It works in DEV environment but not in Production.

Could anyone please advice what's wrong with the code above?

Thank you.

like image 502
Nil Pun Avatar asked Jun 13 '11 23:06

Nil Pun


2 Answers

Convert.ToDateTime uses current culture information about DateTime format. Try something like this:

string format = "dd/MM/yyyy hh:mm tt";
string stringDate = DateTime.Now.ToString(format, CultureInfo.InvariantCulture);
DateTime dateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);
like image 155
Ivan Danilov Avatar answered Nov 15 '22 07:11

Ivan Danilov


Why are you converting from DateTime to string and then back to DateTime?

I think this should work fine:

DateTimeOffset dt = new DateTimeOffset(DateTime.Now);
like image 42
rsbarro Avatar answered Nov 15 '22 08:11

rsbarro