Click here to Skip to main content
6,295,667 members and growing! (17,545 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner License: The Code Project Open License (CPOL)

Localizing Date and Time Display in ASP.NET

By Anthony Leuzzi

Localizing date and time display to meet the user's preferred language
C#, .NET (.NET 1.1, .NET 2.0, .NET 3.0, .NET 3.5), ASP.NET, WebForms, Dev
Posted:3 May 2008
Views:19,057
Bookmarked:28 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
6 votes for this article.
Popularity: 2.76 Rating: 3.55 out of 5
1 vote, 16.7%
1
1 vote, 16.7%
2
1 vote, 16.7%
3
1 vote, 16.7%
4
2 votes, 33.3%
5

Introduction

Date and time information is used in almost every application I write and depending on the business requirements, it may be displayed in one of the following formats; short date, long date, short date time, long date time, etc. This isn't unique by any means, but the method used to format the display of date and time will impact the globalization and localization of your application.

As defined in the MSDN documentation, globalization is the processing of designing and developing applications that function for multiple cultures and localization is the process of customizing application for a given culture and locale. This post is limited to how to localize the display of dates and times in your applications.

Consider for a moment a DataTime object that is initialized to March 9th 2008 12:00 AM. The default ShortDatePattern for the U.S. is M/d/yyyy which displays this date as 3/9/2008. Now consider a user who is accustomed to the ShortDatePattern of d/M/yyyy. Most likely the date in this example will be interpreted as September 3, 2008. This ambiguity can be avoided if you also specify the appropriate CultureIno.

Culture Info

The CultureInfo class contains culture-specific details such as language and sublanguage and also contains objects that contain culture specific information for performing operations such formatting the display of dates, time and numeric values as well as the sorting of strings. The scope of this post is limited to formatting dates and times. You can find a full list of culture names and identifiers in the

There are three types of cultures: invariant, neutral and specific. The invariant culture is culture-insensitive and is associated with the English language but it is not associated with a specific country/region. The neural culture is associated with a language but not a country/region. The specific culture is associated with a language and a country/region.

DateTimeFormatInfo

This class defines how date and times are formatted for a specific culture, but it cannot be used for neutral cultures. There is a set a predefined single character date and time format characters that should meet most of your formatting needs. It is important to note that these format characters are case-sensitive and there cannot contain any white-spaces.

DateAndTimeFormats

Figure 1

I know at least three ways to use the standard format characters. The format character can be replaced with any format characters listed in Figure 1.

string currentDate1 = DateTime.Now.ToString("d");

string currentDate2 = string.Format("{0:d}", DateTime.Now); 

string currentDate3 = string.Format("{0}", DateTime.Now.ToString("d"));        

In the code snippet above, the culture will default to Regional and Language Options of web server. This is not the behavior you would want if the website or application is used by users from multiple cultures. In order to format the date appropriately you must specify the appropriate instance of the CultureInfo object.

string currentDate1 = DateTime.Now.ToString("d", 
    CultureInfo.CreateSpecificCulture("it-IT"));
string currentDate2 = string.Format(CultureInfo.CreateSpecificCulture("it-IT"),
     "{0:d}", DateTime.Now);
string currentDate3 = string.Format("{0}", 
    DateTime.Now.ToString("d", CultureInfo.CreateSpecificCulture ("it-IT")));

In this code snippet, the culture is explicitly set to the Italian language and a country/region of Italy.

Figure2.jpg

Figure 2

We have yet to solve the problem. How do we know what is the user’s preferred language? The answer is contained within the UserLanguages property of the HttpRequest object. This property returns a string array of client language preferences and first element of this array should be considered the preferred language.

private string[] 
languages;protected override void InitializeCulture()
{ languages = Request.UserLanguages;
   if (languages !=null)
   {
      Thread.CurrentThread.CurrentCulture = 
    CultureInfo.CreateSpecificCulture(languages[0]);
   }
}

Figure3.jpg

Figure 3

In IE 7 it is located under Tools | Options and click the languages, and add the desired language. The preferred language is the first item in the list.

In Fire Fox it is located under Tool | Advanced, click Choose and add the desired language.

The InitializeCulure() method is invoked before any of the controls are separated. By resetting the current thread’s culture you will insure that this setting in uniformly set across the entire page; however you not required to do so.

For this example, you will have to add at least one additional language in your preferred browser.

Custom Formatting

%M or M Displays the month number without a leading zero. The ‘%’indicator should be omitted if combined with other format characters.
MM Displays the month with a leading zero.
MMM Displays the abbreviated month name.
MMMM Displays the full month name.
%d or d Displays the day without a leading zero. The ‘%’ indicator should be omitted if combined with other format characters.
dd Displays the day with a leading a zero.
ddd Displays the day names abbreviation.
dddd Displays the full day name.
yy Displays a two digit year without the century.
yyyy Displays the four digit year.
y and yyy Are valid format characters, however not much practical use.
%h or h Displays the hour without aleading zero using the 12 hour clock. The ‘%’ indicator should be omitted if combined with other format characters.
hh Displays the hour with a leading zero using the 12 hour clock.
%H or H Displays the hour without a leading zero using the 24 hour clock. The ‘%’ indicator should be omitted if combined with other format characters.
HH Displays the hour with a leading zero using the 24 hour clock.
%m or m Displays the minute without a leading. The ‘%’ indicator should be omitted if combined with other format characters.
mm Displays the minute with a leading zero
%s or s Displays the second without a leading. The ‘%’ indicator should be omitted if combined with other format characters.
ss Displays the second with a leading zero.
tt The full AM/PM designator
%t or t The first character of the AM/PM designator

If you need more precision when displaying time, there are additional fractions of a second formats which you can find listed in the

MSDN documentation. When creating custom formats be sure not to inadvertently a situation where there can be ambiguity

Conclusion

If you are currently developing applications for a single culture then using the default culture will meet your needs; however if your applications or websites are available on the Internet then you should localize the display of date to use your user’s preferred language.

History

05/02/2008 - Created

License

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

About the Author

Anthony Leuzzi


Member

Occupation: Software Developer (Senior)
Company: Avanti Technologies Corporation
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralBest Localization Plug-in for Visual Studio. PinmemberAlexander Nesterenko22:47 17 Dec '08  
Questioni need to fix date format problem PinmemberNiN9E4:25 13 May '08  
AnswerRe: i need to fix date format problem PinmemberAnthony Leuzzi6:16 13 May '08  
AnswerRe: i need to fix date format problem PinmemberNiN9E7:58 13 May '08  
GeneralRe: i need to fix date format problem PinmemberAnthony Leuzzi9:14 13 May '08  
GeneralUseful PinmemberMurat Firat23:38 3 May '08  
GeneralNice Article PinmemberRazanPaul22:10 3 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 May 2008
Editor:
Copyright 2008 by Anthony Leuzzi
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project