jrsometing
jrsometing

Reputation: 41

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

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

Upvotes: 0

Views: 988

Answers (3)

Abdus Salam Azad
Abdus Salam Azad

Reputation: 5502

You can provide any of your desired Culture like "en-Us", "en-GB" etc. Then all of your datetime will be formatted like that.

DateTimeFormatInfo yourCultureFormat = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", yourCultureFormat)

Upvotes: 0

jrsometing
jrsometing

Reputation: 41

The answer is improved version of @Joel Coehoorn 's answer. GetCultureInfo("xx-XX")) xx like en-EN

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

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415840

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.

Upvotes: 0

Related Questions