简体   繁体   中英

How to format this string so that it can be recognized by Convert.ToDateTime?

I am given this whole string from database:

CCC_0293170118-10-2013-20-27-54.541

I had the substring so that I get 18-10-2013-20-27-54 , but it throws an error

I want to convert it to DateTime so that I can compare it with another DateTime with format like "{10/18/2013 8:28:46 PM} to get the time difference.

You can use "dd-MM-yyyy-HH-mm-ss" format like;

string s = "18-10-2013-20-27-54";
DateTime dt = DateTime.ParseExact(s, "dd-MM-yyyy-HH-mm-ss", CultureInfo.InvariantCulture);
Console.WriteLine(dt);

Output will be;

10/18/2013 8:27:54 PM

Here a demonstration .

A DateTime doesn't have a format. It's just a value.

To parse a value such as "18-10-2013-20-27-54" you should use DateTime.ParseExact (or DateTime.TryParseExact , if it's somewhat-expected that the data may be invalid). So something like:

DateTime value = DateTime.ParseExact(text, "dd-MM-yyyy-HH-mm-ss",
                                     CultureInfo.InvariantCulture);

It's important to specify the invariant culture here to ensure that the Gregorian calendar is used - if you use the "current system culture" then it could use a different default calendar system.

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