29

I have this in my code:

var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

And when my current cultur is dutch (nl-NL) instead of May 1st I get January 5th.

I think the error is in the second parameter dd.MM.yyyy HH:mm:ss.

Is there a way to fix this using the CultureInfo class?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

4 Answers4

48

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
Ronald Wildenberg
  • 31,634
  • 14
  • 90
  • 133
MMK
  • 3,673
  • 1
  • 22
  • 30
6

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    And what about when the culture is en-us? Will I have to code for every single language there is out there? – petko_stankoski Dec 10 '12 at 09:07
  • @Srcee: What do you mean? If the format string is "dd.MM.yyyy", it will never be culture en-us. If you instead mean how to display the date in another culture, then it's another question. You can use `date1.ToString(CultureInfo.CreateSpecificCulture("en-US"))`. – Tim Schmelter Dec 10 '12 at 09:20
0

Try it..It will work

string text="15/03/2021";

DateTime.ParseExact(text, "dd/M/yyyy", CultureInfo.InvariantCulture);