Prithiv
Prithiv

Reputation: 514

DateTime.TryParse works differently in different machines

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.

Upvotes: 1

Views: 1402

Answers (1)

mm8
mm8

Reputation: 169320

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.

Upvotes: 5

Related Questions