Home > Net >  .Net Core Date.ToDateTime() converts in diffrent formats by language
.Net Core Date.ToDateTime() converts in diffrent formats by language

Time:05-28

I create date objects based on strings with hour and minute values coming from a service.

Our app is multi-language, the default Date.ToDateTime() functions work differently in different languages. For example, 01/10/2022 becomes January 10 2022 in some cultures and ``1 October 2022` in others.

What I want is make the function convert to January 10 2022 every time.

How can I do this?

DateTime.Parse(dateString, CultureInfo.InvariantCulture) -> ss1

CodePudding user response:

Instead of Convert.ToDateTime(), you can use DateTime.Parse(), which has overloads to accept an IFormatProvider where you can specify a specific culture.

var dateString = "01/10/2022";
DateTime result = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
// result will ALWAYS have January 10, regardless of culture on local system

See it here:

https://dotnetfiddle.net/NzaYPK

The DateTime.TryParse() function can also do this. For completeness you should be aware of DateTime.ParseExact() and DateTime.TryParseExact() as well.

CodePudding user response:

The answer is improved version of @Joel Coehoorn 's answer.

Datetime newDate = DateTime.Parse(response.Result.TInfo.Date, CultureInfo.GetCultureInfo("xx-XX")).AddHours(hour).AddMinutes(minute);
  • Related