Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime weird behaviour

I have created a C# WinForms application.

On my computer the following works:

DateTime.ParseExact("13/05/2012", "dd/mm/yyyy",  null)

but this doesn't:

DateTime.Parse("13/05/2012")

On my client's computers it's reversed. This works:

DateTime.Parse("13/05/2012")

but this doesn't:

DateTime.ParseExact("13/05/2012", "dd/mm/yyyy",  null)

The error states:

String was not recognized as a valid DateTime.

Didn't manage to find any information on the internet about this problem. The program uses .Net Framework 4 and is a x86 application. I run Windows 8 x64, the client runs Windows 7 x64.

Does anybody have a clue as to why this occurs?

Thanks.

like image 298
Vlad Schnakovszki Avatar asked May 17 '12 20:05

Vlad Schnakovszki


2 Answers

The reason you are getting different behaviour on different computers is because they are running with different cultures. Try running this line of code on both computers to see if it outputs something different: (ideone)

System.Console.WriteLine(CultureInfo.CurrentCulture);

Output (example):

en-US

The culture specifies many things, one of which is the date separator. If you want consistent behaviour for all users, try specifying a culture: (ideone)

CultureInfo cultureInfo = CultureInfo.InvariantCulture; // or whatever you prefer
DateTime dateTime = DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", cultureInfo);

The above code assumes you have these using statements:

using System;
using System.Globalization;
like image 155
Mark Byers Avatar answered Sep 20 '22 17:09

Mark Byers


Be careful; in custom date and time format strings, the mm specifier represents “minutes”, not “months”. You need to use MM for months.

DateTime.ParseExact("13/05/2012", "dd/MM/yyyy",  CultureInfo.InvariantCulture)
like image 43
Douglas Avatar answered Sep 19 '22 17:09

Douglas