Formatting Dates Times and Numbers in ASP - Net - 4GuysFromRolla

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

When you think ASP, think...

Recent Articles
Published: Wednesday, November 10, 2010
All Articles

Formatting Dates, Times and Numbers in ASP.NET


ASP.NET Articles
ASPFAQs.com
Message Board
Related Web By Scott Mitchell
Technologies
User Tips!
Introduction
Coding Tips
Formatting is the process of converting a variable from its native type into a string representation. Anytime you display a
Search
DateTime or numeric variables in an ASP.NET page, you are formatting that variable from its native type into some sort of string
representation. How a DateTime or numeric variable is formatted depends on the culture settings and the format string. Because
dates and numeric values are formatted differently across cultures, the .NET Framework bases its formatting on the specified
culture settings. By default, the formatting routines use the culture settings defined on the web server, but you can indicate that a
Sections: particular culture be used anytime you format. In addition to the culture settings, formatting is also affected by a format string,
Book Reviews which spells out the formatting details to apply.
•Sample Chapters
Commonly Asked The .NET Framework contains a bounty of format strings. There are standard format strings, which are typically a single letter that
Message Board applies detailed formatting logic. For example, the "C" format specifier will format a numeric type as a currency value; the "Y"
Questions
format specifier displays the month name and four-digit year of the specified DateTime value. There are also custom format
JavaScript Tutorials
strings, which display a apply a very specific formatting rule. These custom format strings can be put together to build more
MSDN Communities intricate formats. For instance, the format string "dddd, MMMM d" displays the full day of the week name followed by a comma
Hub
followed by the full name of the month followed by the day of the month. For more involved formatting scenarios, where neither
Official Docs
the standard or custom format strings cut the mustard, you can always create your own formatting extension methods.
Security
Stump the SQL Guru! This article explores the standard format strings for dates, times and numbers and includes a number of custom formatting

Web Hosts
methods I've created and use in my own projects. There's also a demo application you can download that lets you specify a
culture and then shows you the output for the standard format strings for the selected culture. Read on to learn more!
XML

Information: - continued -
Advertise
Feedback
Author an Article Formatting Basics
There are a couple of different ways to format a DateTime or numeric variable. The first way involves using the ToString method,
which has a number of overrides. For DateTime variables:

• DateTime.ToString() - converts the value of the DateTime to a string representation using the current culture and the "G"
format string. (See the table below to see the output of the "G" format string.)
• DateTime.ToString(string) - converts the value of the DateTime to a string representation using the current culture and
the specified format string.
• DateTime.ToString(IFormatProvider) - converts the value of the DateTime to a string representation using the specified
culture settings and the "G" format string.
• DateTime.ToString(string, IFormatProvider) - converts the value of the DateTime to a string representation using the
specified culture settings and the specified format string.

Numeric variables - integers, doubles, decimals, and so on - have the same ToString method and ToString overloads.

Formatting can also be performed using the String.Format method. The String.Format method accepts as input a format string
that contains a number of placeholders, followed by the values to plug into those placeholders. Placeholders take the form {0},
{1}, and so on, and may optional include a format string like so: {0:formatString}. The following code snippet shows using the
String.Format method with three placeholders. The values plugged into these placeholders are a string and two decimal values
that are both formatted as currencies using the "C" format string within the placeholder syntax.

string customerName = "Tito";


decimal subTotal = 245.13;
decimal taxTotal = 18.94;

// OUTPUT FOR EN-US CULTURE: Tito, your order subtotal is $245.13. Tax is $18.94.
string output = string.Format("{0}, your order subtotal is {1:c}. Tax is {2:c}.", customerName,
subTotal, taxTotal);

In the example above, the String.Format method uses the current culture. You can optionally supply the culture settings as the
first parameter to the String.Format method.

Standard Date/Time Format Strings


There are 15 standard date and time format strings defined in the .NET Framework. These 15 format strings are detailed on MSDN
at Standard Date and Time Format Strings. The table below shows these 15 standard format strings, providing a brief description,
code snippet, and sample output using the en-US culture settings. The code snippets reference DateTime.Now, which returns the
current date and time. The output column shows the results when this code was executed on my computer at November 8th, 2010
at 3:39 PM.
Format Description Code Snippet Output
Short date pattern (d) DateTime.Now.ToString("d") 11/8/2010

Long date pattern (D) DateTime.Now.ToString("D") Monday, November 08, 2010

Full date/time pattern - short time (f) DateTime.Now.ToString("f") Monday, November 08, 2010 3:39 PM

Full date/time pattern - long time (F) DateTime.Now.ToString("F") Monday, November 08, 2010 3:39:46 PM

General date/time pattern - short time (g) DateTime.Now.ToString("g") 11/8/2010 3:39 PM

General date/time pattern - long time (G) DateTime.Now.ToString("G") 11/8/2010 3:39:46 PM

Month/day pattern (M) DateTime.Now.ToString("M") November 08

Round-trip date/time pattern (O) DateTime.Now.ToString("O") 2010-11-08T15:39:46.4804000-08:00

RFC 1123 pattern (R) DateTime.Now.ToString("R") Mon, 08 Nov 2010 15:39:46 GMT

Sortable date/time pattern (s) DateTime.Now.ToString("s") 2010-11-08T15:39:46

Short time pattern (t) DateTime.Now.ToString("t") 3:39 PM

Long time pattern (T) DateTime.Now.ToString("T") 3:39:46 PM

Universal sortable date/time pattern (u) DateTime.Now.ToString("u") 2010-11-08 15:39:46Z

Universal full date/time pattern (U) DateTime.Now.ToString("U") Monday, November 08, 2010 11:39:46 PM

Year/month pattern (Y) DateTime.Now.ToString("Y") November, 2010

Keep in mind that the output of the standard format strings depend on the culture settings. For example, formatting November
8th, 2010 using the short date pattern displays 11/8/2010 when using the en-US culture; however, the French (France) culture
(fr-FR) displays 08/11/2010; German (Germany) shows 08.11.2010; and the Japanese culture outputs 2010/11/08. The
download available at the end of this article provides a web page with a drop-down of all available cultures. You can select a
culture and see the output for all of the standard date and time format strings.

If you do not explicitly specify a culture when formatting the .NET Framework uses the current culture settings. For an ASP.NET
application, these are the culture settings defined on the web server, not the culture settings of the user visiting your site. To
learn how to override the web server's culture settings, either for the entire application or on a page-by-page basis, refer to How
to: Set the Culture and UI Culture for ASP.NET Web Page Globalization.

Custom Date/Time Format Strings


There are a variety of custom date and time format strings, which allow the page developer to define intricate formatting logic
through a number of incremental rules. The custom format strings are detailed on MSDN at Custom Date and Time Format
Strings. The table below shows just a few examples of how these custom format strings can be strung together. The code snippets
reference DateTime.Now, which returns the current date and time. The output column shows the results when this code was
executed on my computer at November 8th, 2010 at 3:39 PM.

Format Description Code Snippet Output


Abbreviated month name, day and year DateTime.Now.ToString("MMM d, yyyy") Nov 8, 2010

Day of the week name plus month name and day of month DateTime.Now.ToString("dddd, MMMM d") Monday, November 8

Month/Day/Year, using exactly two digits for each DateTime.Now.ToString("MM/dd/yy") 11/08/10

As with the standard format strings, the individual pieces of the custom format strings are culture-specific. The day of the week
names and month names, for instance, differ based on the culture.

My Date/Time Formatting Methods


Over my years building ASP.NET applications, I've needed alternate formats for date and time variables that aren't supported
by .NET's standard or custom formatting strings. For instance, I have a ToUniversalFormat method that is similar to the "U"
format string, but is more compact. In many applications I opt to show DateTime variables as relative times. For example, rather
than showing the exact date and time a post was made it is often a better idea to show a relative time, like, "A few minutes ago,"
or, "Six days ago." As discussed in Advice for Storing and Displaying Dates and Times Across Different Time Zones, displaying
relative times removes any issues with time zone differences between the web server and visitors, which is why I prefer this
formatting tactic.

These custom formatting methods of mine are implemented as extension methods. Extension methods allow for a developer to
seemingly add methods to an existing type (such as the DateTime type). Consequently, my methods - ToRelativeDateString
and ToUniversalFormat - look as if they're methods defined on the DateTime structure rather than methods I created. This is the
beauty of extension methods. In the demo available for download these extension methods can be found in the App_Code folder.

Some of the code snippets below reference DateTime.Now, which returns the current date and time. The output column shows the
results when this code was executed on my computer at November 8th, 2010 at 3:39 PM.

Format Description Code Snippet Output


Relative time for date more than a var birthDate = new DateTime(2008, 9, 1 9, 45, 0);
on September 1, 2008
year ago birthDate.ToRelativeDateString()

Relative time for date several DateTime.Now.AddMonths(-6).ToRelativeDateString() on May 8


months ago

Relative time for date five days DateTime.Now.AddDays(-5).ToRelativeDateString() five days ago
ago

Relative time for yesterday DateTime.Now.AddDays(-1).ToRelativeDateString() yesterday

DateTime.Now.AddHours(-3.14159).ToRelativeDateString()
Relative time for several hours ago three hours ago

Relative time for more than five DateTime.Now.AddMinutes(-6.25).ToRelativeDateString() six minutes ago
minutes ago

Relative time for less than five DateTime.Now.AddMinutes(-2.5).ToRelativeDateString() a few minutes ago
minutes ago

Relative time for within past DateTime.Now.AddSeconds(-15).ToRelativeDateString() less than a minute ago
minute

Universal format for date in DateTime.Now.ToUniversalFormat() Monday, Nov 8 at 3:39


current year PM

Universal format for date in other var birthDate = new DateTime(2008, 9, 1 9, 45, 0); Monday, Sep 1, 2008 at
year birthDate.ToUniversalFormat() 9:45 AM

Standard Numeric Format Strings


There are nine standard numeric format strings defined in the .NET Framework. These format strings are detailed on MSDN at
Standard Numeric Format Strings. The table below shows these nine standard format strings, providing a brief description, code
snippet, and sample output using the en-US culture settings. Note that some of these format strings allow an option precision to
be specified, which affects how many significant digits or how many digits after the decimal place are displayed. For these I've
included an example specifying an explicit precision value, which is why there are more than nine rows in the table below.

Format Description Code Snippet Output


Currency with default precision (C) 3.14159.ToString("C") $3.14

Currency with specified precision (CN) 3.14159.ToString("C4") $3.1416

Decimal with default precision (D) 32534.ToString("D") 32534

Decimal with specified precision (DN) 32534.ToString("D10") 0000032534

Exponential (E) 123456789.ToString("E") 1.234568E+008

Fixed point with default precision (F) 3.14159.ToString("F") 3.14

Fixed point with specified precision (FN) 3.14159.ToString("F4") 3.1416

General with default precision (G) 3.14159.ToString("G") 3.14159

General with specified precision (GN) 3.14159.ToString("G2") 3.1

Number with default decimal places (N) 3.14159.ToString("N") 3.14

Number with specified decimal places (NN) 3.14159.ToString("N3") 3.142

Percent with default decimal places (P) 0.8752.ToString("P") 87.52 %

Percent with specified decimal places (PN) 0.8752.ToString("P0") 88 %

Round-trip (R) 3.14159.ToString("R") 3.14159

Hexadecimal (X) 183.ToString("X") B7

As with the date and time format strings, the numeric formatting is culture-sensitive. Different cultures use different grouping
separators (commas vs. spaces vs. periods), different currency symbols, and different decimal place characters (periods vs.
commas). Be sure to download the demo to view how formatted numbers look differently with alternative culture settings.

Custom Numeric Format Strings


There are a few custom numeric format strings, which allow the page developer to define intricate formatting logic through a
number of incremental rules. The custom format strings are detailed on MSDN at Custom Numeric Format Strings. The table below
shows just a few examples of how these custom format strings can be strung together. As with the standard format strings, the
individual pieces of the custom format strings are culture-specific. For example, the group separator and decimal point displayed
depend on the configured culture.

Note the selection separator format string, which allows you to specify different formats for when a number is positive, negative,
and zero. The format string #,000.00;(#,000.00);Zero says, "Use the format string #,000.00 when the number is positive,
(#,000.00) when it's negative, and Zero when it's zero." The last three rows in the grid below show how the appropriate format
string is applied based on the value of the number being formatted.

Format Description Code Snippet Output


Zero placeholder (0) 3.14.ToString("00.0000") 03.1400

Zero placeholder (0) 123.45678.ToString("00.0000") 123.4568

Digit (#) and zero (0) placeholders 3.14.ToString("#0.000#") 3.140

Digit (#) and zero (0) placeholders 123.45678.ToString("#0.000#") 123.4568

Group separator placeholder (,) 123456.ToString("#,000.00") 123,456.0

Group separator placeholder (,) 123456789.ToString("#,000.00") 123,456,789.0

Group separator placeholder (,) 123456789876.ToString("#,000.00") 123,456,789,876.0

Section separator (;) 12345.67.ToString("#,000.00;(#,000.00);Zero") 12,345.67

Section separator (;) (-12345.67).ToString("#,000.00;(#,000.00);Zero") (12,345.67)

Section separator (;) 0.ToString("#,000.00;(#,000.00);Zero") Zero


My Numeric Formatting Methods
I have a number of numeric formatting methods I've used in my projects over the years. There's the ToAbbreviatedFormat
method, which is useful when displaying larger integer numbers in a confined space when the actual number itself isn't as
important as the relative size. For instance, ToAbbreviatedFormat displays a number like 45,431 as 45k. There's also a
ToStringAsText method that displays the integer numbers one through ten as English, rather than as a number.

Format Description Code Snippet Output


Abbreviated format (less than 1,000) 34.ToAbbreviatedFormat() 34

Abbreviated format (greater than 1,000) 9876.ToAbbreviatedFormat() 9k

Abbreviated format (greater than 1,000) 12345678.ToAbbreviatedFormat() 12,345k

To string as text (capitalized) 3.ToStringAsText(true) Three

To string as text (not capitalized) 6.ToStringAsText(false) six

To string as text (greater than 10) 1234.ToStringAsText(false) 1,234

Conclusion
Formatting is a common task in an ASP.NET application and, not surprisingly, the .NET Framework offers a number of techniques
for formatting both DateTime and numeric variables. Formatting a date, time, or numeric value involves two parameters - the
culture settings and a format string. If omitted, the current culture is used and a default format string is assumed. The format
string can be either a standard format string or one built from the various custom format strings. Additionally, you can create your
own formatting methods for scenarios that cannot be handled by the existing formatting strings.

Happy Programming!

• By Scott Mitchell

Attachments:
• Download the Demo Code Used in this Article

Further Reading
• Standard Date and Time Format Strings
• Custom Date and Time Format Strings
• Standard Numeric Format Strings
• Custom Numeric Format Strings
• Extending Base Type Functionality with Extension Methods

ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article

Property of Quinstreet Enterprise.


Terms of Service | Licensing & Reprints | About Us | Privacy Policy | Advertise
Copyright 2016 QuinStreet Inc. All Rights Reserved.

You might also like