Sjoemeleboem Software

Home of Paul Deen

VB, .NET, SQL Server, MOSS

Programming for life!

Serving the web community
with my knowledge

››› See the latest news

Date formatting

To avoid problems with parsing dates in different countries, the best thing to do is to use ISO notation internally. It may also be better to use it for display, but some users might disagree on that.

The problem

As a programmer, you are probably aware of problems with dates. If not, I'll tell you now.

If you have to parse a date from a string, you need to know the format. You can use several characters for separation of the different parts (day, month and year) and you can put them in diffent orders.
Some examples:

  • dd-mm-yyyy
  • mm/dd/yyyy
  • dd.mm.yyyy
  • yyyy-mm-dd

The solution

The magic word here is: ISO! If you use yyyy-mm-dd notation, you can never make mistakes. There is no yyyy-dd-mm notation, so if you see two minus characters (-) and the first part contains 4 digits, it's ISO. You can parse it on any computer in any country, with any regional setting. It will never fail. (as long as you use the right routines...)
In .NET, you can use the DateTime.Parse method to do this.

Believe me, it will save you a lot of headaches.

Besides, this formatting has another advantage: you can use text sorting on this field in any control like DataGrid or ListView, it will always sort. It is much more consistent to place the different parts of the date in order: first year, then month, then day. If the day increases, the last part of the date will increase. If there is a new month, the last part of the date will be reset to one, and the month will be increased. After 12 months, the month and day will be reset to 1, and the year will be increased. This makes perfect sense!

Example code (C#)

string myStringContainingSomeDate = "2005-09-17";
DateTime myDate = DateTime.Parse(myStringContainingSomeDate);

ASP.NET

For formatting dates in either ASP.NET, simply use the globalization tag in web.config file to specify the date format used:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="nl-NL"
uiCulture="nl-NL"
/>
</system.web>

You change the culture and uiCulture attributes of the globalization tag to specify the regional settings.

Last modified on: 2005-09-22