简体   繁体   中英

Formatting date to specific format

What is the best way to format a string date to a specific format?

For example if input was 30/09/2014 it would be formatted as 2014-09-30 or any other similar date format for the former?

First of all, DateTime doesn't have any implicit format. Strings have.

Sounds like you just need to parse your string and format it with DateTime.ToString() method like;

string s = "30/09/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture).Dump();
    // Result will be 2014-09-30
}

Since I create this example on LINQPad , .Dump() is just an extension method.

Just be careful when you parse a string that have / as a date separator. "/" custom format specifier has a special meaning of replace me with the current culture of specified culture date separator . That means, your CurrentCulture or specified culture's DateSeparator property is not / , your parsing operation will fail even if your string and format are the same format.

That's why I used InvariantCulture in my example since it has / as a DateSeparator .

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