c# convert date from DateTimePicker into String

67 Views Asked by At

I try to convert something like this: "Wednesday, 21. January 2024" into this: "03.01.2024". How can I do this in c#?

I will use it for a program. There is an DateTimePickerand I will convert the output into a String.

Edit: The original input is in German...

thanks Laurin

1

There are 1 best solutions below

0
Dmitry Bychenko On BEST ANSWER

Please, note that 21 January is Sunday, not Wednesday, let's change 21 to 3 and perform a standard trick: parse text into DateTime and then format it into desired string representation:

using System.Globalization;

...

string text = "Wednesday, 3. January 2024";

var result = DateTime
  .ParseExact(text, "dddd', 'd'. 'MMMM' 'yyyy", CultureInfo.InvariantCulture)
  .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture);

If original text is in German (Deutsch culture, say de-DE) it should be

Mittwoch, 3. Januar 2024

and we have

string text = "Mittwoch, 3. Januar 2024";
           
var result = DateTime
  .ParseExact(text, "dddd', 'd'. 'MMMM' 'yyyy", CultureInfo.GetCultureInfo("de-DE"))
  .ToString("dd.MM.yyyy", CultureInfo.GetCultureInfo("de-DE"));

Finally, you can try using current culture (German on your workstation)

string text = "Mittwoch, 3. Januar 2024";
           
var result = DateTime
  .ParseExact(text, "dddd', 'd'. 'MMMM' 'yyyy", CultureInfo.CurrentCulture)
  .ToString("dd.MM.yyyy");