mpaton
mpaton

Reputation: 789

DateTime.Parse, Latvian culture settings

I am sending in a string in dd/MM/yyyy format, which is then being parsed into lv-LV culture as set per the web.config globalization setting.

I am then comparing the date to DateTime.Now to see if it is in the past.

The problem is, DateTime.Parse converts my string to dd.MM.yyyy format, but DateTime.Now has MM.dd.yyyy format, so the comparison always fails.

Why would DateTime.Now be different to the output from DateTime.Parse, on the same thread culture?

Thanks!

(Update) This is the code I am using:

InputText contains input from a form in DD.MM.YYYY format

DateTime date = DateTime.Parse(InputText, CultureInfo.CurrentCulture);
// Check it's not in the past
this.IsValid = (date.CompareTo(DateTime.Now) > 0);

[DateTime.Now] in this context is in MM.DD.YYYY format using lv-LV cultureInfo [date] is in DD.MM.YYYY format after the DateTime.Parse

Upvotes: 0

Views: 1554

Answers (2)

Antoine
Antoine

Reputation: 5245

If you just want to compare the 2 dates, you don't need to convert to string first.

DateTime myDate = DateTime.Parse(myDateAsString);//with the correct locale to ensure it's correctly parsed
if (myDate < DateTime.Now)
{
  //it's in the past
}

Upvotes: 1

Oded
Oded

Reputation: 499002

A DateTime does not have formatting - it is simply a point in time.

If you are viewing it, that means you are outputting it. Use the correct culture to output the date.

DateTime.ToString has overloads that take a format provider such as a CultureInfo:

string formatted = DateTime.ToString(new CultureInfo("lv-LV"));

If not specified (in code or configuration), the default system culture will be used (or CultureInfo.InvariantCulture, in some cases).

Upvotes: 2

Related Questions