1

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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
user667430
  • 1,487
  • 8
  • 38
  • 73
  • Do a .ToString() on the DateTime object and specify the format you like: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx. however if you are already looking at a string date then you should convert it to a datetime object and then get the string format to your liking – Ahmed ilyas Oct 01 '14 at 12:51
  • 4
    It's not really clear what you've tried so far, or whether you're looking for parsing as well as formatting advice. Calling `DateTime.ToString` with a custom format string is probably want you want here... – Jon Skeet Oct 01 '14 at 12:51

1 Answers1

8

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.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364