Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Best way to convert string date format to another string?

Tags:

c#

datetime

I have the following date stored as a string

  04.09.2009 (dd.mm.yyyy)

Now I would like it changed to this format:

  2009/08/31 (yyyy/mm/dd)

Remember output should be a string value and the input date is a string.

What is the best way to convert it with minimal effort?

like image 242
JL. Avatar asked Nov 28 '22 20:11

JL.


1 Answers

Why are you storing the date as a string? That's generally a bad idea...

To convert the string you parse it into a DateTime value, the format that into a string:

string newFormat = DateTime.ParseExact(theDate, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'/'MM'/'dd")

(Note that you need apostrophes around the slashes to get the literal character, otherwise it will use the date separator character of the culture, which may be a different character.)

like image 170
Guffa Avatar answered Dec 15 '22 09:12

Guffa