1

I'm using following code in my project but "DateTime.TryParse" gives different results in different machine. IsDate method returns "False" on my machine and return "True" on another machine.

if(IsDate("30/03/2020 04:00",out dt))
{
}

private bool IsDate(object o, out DateTime date)
{
    return DateTime.TryParse(o.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out date);
}

I have also tried "DateTime.TryParseExact" as per in below article, but no use. https://github.com/dotnet/runtime/issues/25120

Please suggest me any ideas to make it work properly.

Thanks.

Prithiv
  • 504
  • 5
  • 20
  • set culture https://stackoverflow.com/a/51603215/1071165 – Mertuarez Apr 09 '20 at 10:01
  • This is expected. In a machine where the local Culture defines the Date format as "dd/MM/yyyy", the string will be parsed correctly. In another, where the Date format is defined as "MM/dd/yyyy", it will fail. Or, worse, it will succeed, if the input is, e.g., `"09/04/2020"`: it will be parsed as the 4th of September instead of the 9th of April. If this string comes from User input, you need to provide means to enter a DateTime value in a specific (invariant) format (e.g., using a DateTimePicker or input *fields* where the Month, Day and Year are entered separately, or specify the input format) – Jimi Apr 09 '20 at 15:25
  • If this is instead a fixed format, coming from a file, for example, you need to determine its format and use a fixed format to parse it (thus using `TryParseExact()`). If the DateTime format is from a logging system or other source that saves data to a text file, where the date, because of a rather gigantic mistake, is saved using the local Culture settings, then you're forced to use the CultureInfo of the Machine where this output was generated. If the source is a database, fire whomever had the idea of using strings as DateTime values. And so on... – Jimi Apr 09 '20 at 15:26

1 Answers1

5

Replace CultureInfo.CurrentCulture with a fixed culture like for example CultureInfo.InvariantCulture:

private bool IsDate(object o, out DateTime date)
{
    return DateTime.TryParse(o.ToString(), System.Globalization.CultureInfo.InvariantCulture, 
        DateTimeStyles.None, out date);
}

CultureInfo.CurrentCulture is a per-thread setting/property that defaults to the user settings on the machine.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Hi, I have tried this but it is not working. Still i'm getting "False" from "IsDate" method. – Prithiv Apr 09 '20 at 09:56
  • 1
    @Prithiv: `ParseExact` should give the same result assuming that you use the same culture. – mm8 Apr 09 '20 at 09:57