简体   繁体   中英

c# datetime string format

Can't seem to get this one right. What format string should I use for the following DateTime input ?

2013-08-24T19:29:26.4050000

I want to extract the date.

I tried:

DateTime.ParseExact(localTime, "yyyy-MM-ddTHH:mm:ss.fffffff", null).ToString("yyyy-MM-dd");

But this doesn't work for me, plus I feel there must be a way to avoid the multiple "f" at the end (I just need the date, don't care about the hour)

Thanks, Li

You didn't gave us any information about your error and since we don't know your culture, here and it works with InvariantCulture ;

string localTime = "2013-08-24T19:29:26.4050000";
DateTime date = DateTime.ParseExact(localTime, "yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Console.WriteLine(date.ToString("yyyy-MM-dd"));

Output will be;

8/24/2013 7:29:26 PM
2013-08-24

Here a DEMO .

This looks like the format of XMLDateTime use XmlCovert for this purpose.

string fmt = "2013-08-24T19:29:26.4050000";
var dt = XmlConvert.ToDateTime(fmt, XmlDateTimeSerializationMode.Unspecified);
Console.WriteLine(dt);

Ideone Demo

Looks like you are parsing an ISO 8601 datetime string. This article Parsing ISO 8601 string to DateTime in .NET? seems to be the one you're looking for

You can also try the below solution to get the result in dd/MMM/yyyy format in string variable:

string _dateTime=string.Empty;

_dateTime=localTime.ToString(dd/MMM/yyyy);

So for the date 2013-08-24T19:29:26.4050000 will return you as 24/Aug/2013

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