CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> .NET / C# >> C# >> Date & Time >> Formatting


Formatting Date and Time Values In .NET
Rating:

Bradley Jones (view profile)
January 24, 2003

Environment: .NET

The .NET Framework provide a class for working with dates and times—the DateTime class located in the System namespace. The DateTime class stores both a full date and the full time.


(continued)



The DateTime class has a number of properties and methods that you will find useful. Additionally, there are a couple of static members. The two static properties that you will be likely to use are Now and Today. Now contains the date and time for the moment the call is made. Today returns the current date. You should note that although the Today property gives you only a valid date. It does not give you the current time, even though you can access time members.

Because these are static properties, their values can be obtained using the class name rather than an instant name. In other words, to get the current date or the current time, you need only do the following:

DateTime.Now

DateTime.Today

These commands assume that you have included the System namespace. If you didn't include the namespace, then you'll need to fully qualify the names:

System.DateTime.Now

System.DateTime.Today

You can review the online documents for information on all the methods and properties in DateTime. A few of the ones you might find useful are:

Date
Returns the date portion of a DateTime object
Month
Returns the month portion of a DateTime object
Day
Returns the day of the month of a DateTime object
Year
Returns the year portion of the DateTime object
DayOfWeek
Returns the day of the week of a DateTime object
DayOfYear
Returns the day of the year of a DateTime object
TimeOfDay
Returns the time portion of a DateTime object
Hour
Returns the hour portion of a DateTime object
Minute
Returns the minutes portion of a DateTime object
Second
Returns the seconds portion of a DateTime object
Millisecond  
Returns the milliseconds component of a DateTime object
Ticks
Returns a value equal to the number of 100-nanoseconds ticks for the given DateTime object

Formatting the Date and Time

When you work with strings and other output, you can use specifiers to indicate that formatting should occur. One of the most common times when specifiers are used is when using one of the System.Console classes, Write or WriteLine.

There are a number of specifiers that can be used specifically with dates, times, or both. These include the capability of displaying information in short and long format. Table 1 contains the date and time specifiers.

Table 1. Date And Time Formatting Characters

SpecifierDescription Default FormatExample Output
dShort datemm/dd/yyyy5/6/2001
DLong dateday, month dd, yyyySunday, May 06, 2001
fFull date/short timeday, month dd, yyyy hh:mm AM/PMSunday, May 06, 2001 12:30 PM
FFull date/full timeday, month dd, yyyy HH:mm:ss AM/PMSunday, May 06, 2001 12:30:54 PM
gShort date/short timemm/dd/yyyy HH:mm6/5/2001 12:30 PM
GShort date/long timemm/dd/yyyy hh:mm:ss6/5/2001 12:30:54 PM
M or mMonth daymonth ddMay 06
R or rRFC1123ddd, dd Month yyyy hh:mm:ss GMTSun, 06 May 2001 12:30:54 GMT
sSortable yyyy-mm-dd hh:mm:ss2001-05-06T12:30:54
tShort timehh:mm AM/PM12:30 PM
TLong timehh:mm:ss AM/PM12:30:54 PM
uSortable (universal) yyyy-mm-dd hh:mm:ss2001-05-06 12:30:54Z
USortable (universal) day, month dd, yyyy hh:mm:ss AM/PMSunday, May 06, 2001 12:30:54 PM
Y or yYear/monthmonth, yyyyMay, 2001
s is used as a specifier for printing a sortable date. Note that this is a lower case s. An uppercase S is not a valid format specifier and will generate an exception if used.

The date and time specifiers are easy to use. Listing 1 defines a simple date variable and then prints it in all the formats presented in Table 1.

Listing 1. dtformat.cs—The Date Formats

 1:  // dtformat.cs - date/time formats
 2:  //-----------------------------------------------
 3:
 4:  using System;
 5:
 6:  class myApp
 7:  {
 8:    public static void Main()
 9:    {
10:       DateTime CurrTime = DateTime.Now;
11:
12:       Console.WriteLine("d: {0:d}", CurrTime );
13:       Console.WriteLine("D: {0:D}", CurrTime );
14:       Console.WriteLine("f: {0:f}", CurrTime );
15:       Console.WriteLine("F: {0:F}", CurrTime );
16:       Console.WriteLine("g: {0:g}", CurrTime );
17:       Console.WriteLine("G: {0:G}", CurrTime );
18:       Console.WriteLine("m: {0:m}", CurrTime );
19:       Console.WriteLine("M: {0:M}", CurrTime );
20:       Console.WriteLine("r: {0:r}", CurrTime );
21:       Console.WriteLine("R: {0:R}", CurrTime );
22:       Console.WriteLine("s: {0:s}", CurrTime );
23:  //     Console.WriteLine("S: {0:S}", CurrTime );  // error!!!
24:       Console.WriteLine("t: {0:t}", CurrTime );
25:       Console.WriteLine("T: {0:T}", CurrTime );
26:       Console.WriteLine("u: {0:u}", CurrTime );
27:       Console.WriteLine("U: {0:U}", CurrTime );
28:       Console.WriteLine("y: {0:y}", CurrTime );
29:       Console.WriteLine("Y: {0:Y}", CurrTime );
30:    }
31:  }

The output from this listing is:

d: 5/6/2002
D: Sunday, May 06, 2002
f: Sunday, May 06, 2002 1:06 PM
F: Sunday, May 06, 2002 1:06:51 PM
g: 5/6/2002 1:06 PM
G: 5/6/2002 1:06:51 PM
m: May 06
M: May 06
r: Sun, 06 May 2002 13:06:51 GMT
R: Sun, 06 May 2002 13:06:51 GMT
s: 2002-05-06T13:06:51
t: 1:06 PM
T: 1:06:51 PM
u: 2002-05-06 13:06:51Z
U: Sunday, May 06, 2002 6:06:51 PM
y: May, 2002
Y: May, 2002

In line 10, this listing declares an object to hold the date and time. This is done using the DateTime class. This object is called CurrTime. It is assigned the static value from the DateTime class, Now, which provides the current date and time. Looking at the output, you can see that it was midday in May when I ran this listing. Lines 12 to 29 present this same date and time in all the date/time formats.

Line 23 is commented. This line uses the S specifier, which is not legal. If you uncomment this line, you will see that the listing throws an exception.

For More Information...

I'll be posting a few additional aritcles on formatting. The next article will be on causing different formatting to occur based on whether a number is positive or negative. Additionally, you can get more information from my books,
Sams Teach Yourself C# in 21 Days and Sams Teach Yourself the C# Language in 21 Days.

About the Author
Bradley Jones, CodeGuru Site Manager, is a Microsoft MVP that works for Jupitermedia as an Executive Editor over many of the software development sites and channels. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days.

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
date without year - hfr (04/07/2005)
Daveloper - kdpo1990 (12/27/2004)
Interesting article - dwillms (03/14/2004)
Q: Convert string to DateTime ??? - Legacy CodeGuru (08/21/2003)
why the value of millisecond is zero? - Legacy CodeGuru (02/05/2003)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES