Furkan Gözükara
Furkan Gözükara

Reputation: 23800

When parsing datetime into month day with English culture, it is still parsed in Turkish language

Here is the code. I still get incorrect results

string srRegisterDate = "25.07.2009 00:00:00"
CultureInfo culture = new CultureInfo("en-US");
srRegisterDate = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate), culture);

The result is Cumartesi, Temmuz 25, 2009

Instead it should be Saturday, July 25, 2009

How can i fix this error?

C#.net v4.5.2

Upvotes: 9

Views: 2891

Answers (3)

CheGueVerra
CheGueVerra

Reputation: 7963

This works

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo trDtfi = new CultureInfo("tr-TR", false).DateTimeFormat;
string result = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate, trDtfi).ToString(usDtfi));

original

25.07.2009 00:00:00

transformed

7/25/2009 12:00:00 AM

EDIT

Was one to short of required

string test = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(Convert.ToDateTime(srRegisterDate, trDtfi).ToString(usDtfi)));

Saturday, July 25, 2009

Upvotes: -1

Soner Gönül
Soner Gönül

Reputation: 98740

Convert.ToDateTime(srRegisterDate) still uses your CurrentCulture which looks like tr-TR based on day and month names. Cumartesi - Temmuz

In String.Format, your culture will be ignored since you used it as a third parameter as an argument but you never use it.

Your code called Format(string format, object arg0, object arg1) overload. But you never use the arg1. This overload doesn't think this is a culture. It thinks it is another argument that you want to format.

This String.Format has an overloads that takes IFormatProvider as a first argument.

For example;

srRegisterDate = String.Format(culture, "{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate));

But most comman way (and I always prefer) to get the result that you want is using .ToString() method like;

srRegisterDate = Convert.ToDateTime(srRegisterDate).ToString("dddd, MMMM d, yyyy", culture);

Upvotes: 7

Habib
Habib

Reputation: 223217

The issue is because of ignored culture value in String.Format and not with converting string to DateTime.

You need:

srRegisterDate = String.Format(culture, "{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate));

Your current call to String.Format utalizes the overload String.Format Method (String, Object[]) and the culture passed in parameter is treated as a simple object parameter passed for place holder. Since there is no place holder, you don't even see it getting ignored.

If you want to have culture utilized in String.Format then you have to use the overload : Format(IFormatProvider, String, Object) or String.Format Method (IFormatProvider, String, Object[])

Upvotes: 5

Related Questions