0

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

mpaton
  • 789
  • 3
  • 14
  • I think you need to show us some more complete code; a `DateTime` (such as `.Now`, or the result of a `.Parse`) doesn't *have* a format of its own - ddmm versus mmdd is a property of *string representations*, not of `DateTime` values themselves. – AakashM Dec 01 '10 at 15:57
  • are you comparing two dates as strings? if you are comparing two datetime structures, it should not matter what culture the toString is representing. – Alex Dec 01 '10 at 16:03

2 Answers2

2

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).

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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
}
Antoine
  • 5,055
  • 11
  • 54
  • 82