Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET / .NET4

DateTime format in .NET 4.0

5.00/5 (5 votes)
10 Oct 2011CPOL 22.2K  
If you have different DateTime pattern (especially separator) in the locale
Lets assume I have the DateTime pattern "dd-MMM-yyyy" in my locale.

DateTime.Now.ToString("yyyy/MM/dd") working different in 3.5 & 4.0 framework.

In 3.5, it uses the pattern given in the parameter to convert the date to string. So, the output would be "2011/11/10" and it the expected result.

But in 4.0, this would return as "2011-11-10" which is not correct. 4.0 is using the current culture's ("-") separator instead of using the pattern's separator ("/") given in the parameter. To fix it, we need to pass IFormatProvider along with the ToString function.

Eg:
C#
DateTime.Now.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)