简体   繁体   中英

How to convert this date time string?

I am getting this date time string from Sharepoint:

2013-01-01 08:00:00:000

I want to convert it to

2013-01-01 08:00:00 AM

Any ideas how to do that? Every time I try to use Date.Parse, I get an error saying the string is not a valid date time type

Best option is parsing it to DateTime and get it's string representation with a specific format.

string s = "2013-01-01 08:00:00:000";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("yyyy-MM-dd HH:mm:ss tt", CultureInfo.InvariantCulture).Dump();
    // 2013-01-01 08:00:00 AM
}

Based on Jon's comment , you can use ParseExact as well.

DateTime dt = DateTime.ParseExact("2013-01-01 08:00:00:000",
                                  "yyyy-MM-dd HH:mm:ss:fff", 
                                  CultureInfo.InvariantCulture);
string s = dt.ToString("yyyy-MM-dd HH:mm:ss tt", CultureInfo.InvariantCulture);

Or you can format directly that ParseExact return value;

string s = DateTime.ParseExact("2013-01-01 08:00:00:000",
                               "yyyy-MM-dd HH:mm:ss:fff", 
                               CultureInfo.InvariantCulture)
                   .ToString("yyyy-MM-dd HH:mm:ss tt", 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