0

I've just started using C#. I'm trying to create a static method that takes a string as such; 2018-03-15T08:50:00-05:00 and converts it to Mar 3, 2018. I've researched this for a long time but none of the questions seem to convert to this format, rather all of the answers convert to dd-mm-yyyy.

I think it would be something like this:

public static string ToProperDate(this string input)
    {
       return String.Format("{0:dddd, MMMM d, yyyy}", input);
    }

Could someone please help me? Thank-you so much.

user180708
  • 407
  • 1
  • 4
  • 16
  • Possible duplicate of [WPF format DateTime in TextBlock?](https://stackoverflow.com/questions/1333052/wpf-format-datetime-in-textblock) – Peter May 14 '18 at 14:19

1 Answers1

5

You should parse the text to a DateTime first to ease formatting it.

So change the input to a DateTime instance:

public static string ToProperDate(this DateTime input)
{
   return String.Format("{0:dddd, MMMM d, yyyy}", input);
}

Or parse it in your method:

public static string ToProperDate(this string input)
{
   DateTime d = DateTime.Parse(input);

   return String.Format("{0:dddd, MMMM d, yyyy}", d);
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • or `public static string ToProperDate(this DateTime input) => string.Format("{0:dddd, MMMM d, yyyy}", input);` :) – aloisdg May 14 '18 at 14:19
  • That is the same as my answer @aloisdg – Patrick Hofman May 14 '18 at 14:19
  • Will DateTime.Parse treat ISO 6801 string representation independent of the current culture? I know that's true for SQL Server, but is it true for .Net as well? – Zohar Peled May 14 '18 at 14:19
  • Yes, I believe it is one of the default conversion formats. – Patrick Hofman May 14 '18 at 14:20
  • 1
    Yes, you are correct. Good to know!, as it turns out, it's documented in the remarks section, under the title **Parsing and cultural conventions** - All overloads of the Parse method are culture-sensitive unless the string to be parsed conforms to the ISO 8601 pattern. – Zohar Peled May 14 '18 at 14:28