简体   繁体   中英

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!

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);

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM