简体   繁体   中英

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.

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;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM