简体   繁体   中英

String was not recognized as a valid DateTime. Throws an Exception

I'm trying to convert current date to a specified format.

DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
                                       CultureInfo.InvariantCulture,
                                       DateTimeStyles.None);

I'm receiving the following exception.

String was not recognized as a valid DateTime.

My local TimeZone is (UTC+10:00)Melbourne.

What am I doing wrong here?

Your code (even if it worked), would do nothing. It would simply serialize and deserialize the date. I believe you're looking for this:

string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

It doesn't work because DateTime.Now.ToString() is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you):

14/01/2016 3:54:01 PM  

Which is of the format:

dd/MM/yyyy h:mm:ss tt

Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff

Try this:

string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);

EDIT:

A better way to achieve the date in the format would be like

    DateTime now = DateTime.Now;
    CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
    Thread.CurrentThread.CurrentCulture = culture;
    Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));

IDEONE DEMO

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