简体   繁体   中英

Convert various datetime formats to an specific one

I'm developing an application where I get various datetime formats from users (like 27/02/2016 12:00:00 AM , 02/28/16 12:00:00 AM , 4/18/2016 00:00:00 ,...) and I have to convert all to M/dd/yyyy h:mm:ss .

I tried:

DateTime.ParseExact(dateText,"M/d/yyyy HH:mm:ss", null);
DateTime.ParseExact(dateText,"M/d/yyyy h:mm:ss tt", null);

I also replaced null by CultureInfo.InvariantCulture , CultureInfo.CurrentUICulture.DateTimeFormat and CultureInfo.CurrentCulture which mentioned in many questions about converting string to datetime.

But I always get:

String was not recognized as a valid DateTime

I can convert 27/02/2016 12:00:00 AM if I code like this:

DateTime.ParseExact(dateText,"d/M/yyyy hh:mm:ss tt", null);

But that's not what I want.

Is there anyway to convert any datetime format to M/dd/yyyy HH:mm:ss using one line code or at least a method?

If you know what all the possible formats are then you should call the overload of DateTime.TryParseExact that takes an array of allowable formats. Otherwise, you should probably call DateTime.TryParse , which will test all possible standard formats for the current culture.

If you know for a fact that the text is valid then you can use ParseExact or Parse instead and then call ToString directly on the result. If you do use one of the Try methods then you'll first have to test whether the conversion was successful and, if it is was, then you can call ToString on the result.

You can convert it like this :

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

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