coffeeak
coffeeak

Reputation: 3120

convert string to datetime format invalid System.Datetime

I have been trying many different solutions found here but none works. I want to convert the string to the format of dd/MM/yyyy

editField["ExpiryTime"] = "5/19/2011 12:00:00 AM";
DateTime dt = DateTime.ParseExact(editField["ExpiryTime"].ToString(), "dd/MM/yyyy HH:mm:ss tt",  CultureInfo.InvariantCulture);

But I always get an error of invalid System.DateTime. Pleaes help!

Upvotes: 1

Views: 3275

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460018

Use CultureInfo.InvariantCulture to avoid culture issues like invalid date separators and this format:

M/dd/yyyy hh:mm:ss tt

Uppercase M is for months, dd are the days, yyyy the four digit years. Lowercase hh are the hours in 12h format(required in combination with AM/PM), mm are the minutes, ss the seconds and tt the AM/PM designator.

string input = editField["ExpiryTime"].ToString(); // "5/19/2011 12:00:00 AM"
DateTime dt = DateTime.ParseExact(input, "M/dd/yyyy hh:mm:ss tt",  CultureInfo.InvariantCulture);

I want to convert the string to the format of dd/MM/yyyy

Then use ToString in the same way, CultureInfo.InvariantCulture forces / as date separator, without it will be replaced with your current culture's date-separator:

string result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Upvotes: 2

user240141
user240141

Reputation:

If you need it as string, then you should try this

var dt = string.Format("{0:dd/MM/yyyy}",DateTime.Now);

Note: Also check your local system date time format. If it mismatches with the used one , still you might experience the same exception..

Upvotes: 0

Related Questions