-1

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

2
  • 1
    Are you just asking how to parse a date from a string in C#? This looks like a good place to start: learn.microsoft.com/en-us/dotnet/standard/base-types/… What have you tried and what didn't work as expected? Commented Jan 3, 2024 at 16:35
  • 2
    I recommend you show your work, this will get downvoted. Commented Jan 3, 2024 at 16:35

1 Answer 1

2

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.