Formatting Dates, Times and Numbers in ASP.NET
Posted
on 4 Guys From Rolla
See other posts from 4 Guys From Rolla
Published on
Indexed on
2010/12/06
16:57 UTC
Read the original article
Hit count: 660
Formatting is the process of converting a variable from its native type into a string representation. Anytime you display a 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 particular culture be used anytime you format. In addition to the culture settings, formatting is also affected by a format string, which
spells out the formatting details to apply.
The .NET Framework contains a bounty of format strings. There are standard format strings, which are typically a single letter that applies detailed formatting
logic. For example, the "C" format specifier will format a numeric type as a currency value; the "Y" format specifier displays the month name and four-digit year of
the specified DateTime
value. There are also custom format strings, which display a apply a very specific formatting rule. These custom format
strings can be put together to build more intricate formats. For instance, the format string "dddd, MMMM d" displays the full day of the week name followed by a comma
followed by the full name of the month followed by the day of the month. For more involved formatting scenarios, where neither the standard or custom format strings
cut the mustard, you can always create your own formatting extension methods.
This article explores the standard format strings for dates, times and numbers and includes a number of custom formatting 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!
Read More >
© 4 Guys From Rolla or respective owner