Formatting Date and Time Values In .NET

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.

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

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. 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, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Comments

  • Fake Oakley Batwolf wholesale online

    Posted by klghaflac on 06/26/2013 03:32pm

    ray ban outlet ,It doesn't matter what product, providing careful after years of experience of design, production and market demand is going to be loved through the public. The leading products include women's Oakley sunglasses, ski goggles, motocross goggles, golf series, leisure series, special compilation of five major categories, together with hats, T-shirts, handbags along with other peripheral products. fake oakley sunglasses ,Oakley had in days gone by several years, the will of the baby. Virtually every project, designed, plus the cultivation of personal feeling behind, and continue to be one of the best sunglasses in a very set of two the planet earth. An easy range, from contemporary design to some more classic, traditional design, beautiful neutral colors, including black, green, brown, cream and gray color palette. Fake Oakley Jawbone ,Oakley sunglasses are not only stop the sun, but the other hit the decorative surface. The stylish appearance and fashion style, it'll be your sensible choice. Oakley is very perfect! Nevertheless , there a wide range of artisans top brand sunglasses, Oakley accept to accept their particular time and has become added is actually strange architecture and innovative distance limitations. Comfortable as a set of two modest sunglasses sunglasses more than a few dark lens held by way of a framework, as a way to maintain from the Gulf harmful rays, that is certainly no chance as a result. Oakley sports sunglasses better sunglasses sold to get. You can find a framework and coated lenses to adjust to every face type. An issue on how to opt for a set of two fashion OAKLEY sunglasses cheap women. Did you know what, besides women's fashion OAKLEY sunglasses can enhance their vision problems, nonetheless they also permit them to are more trendy and fashionable. Cheap Oakley sunglasses, the technique of subversion it's comfortable, practical, artistic, and integration glasses. A scale of Oakley sunglasses has built numerous and have to pay to cut back significantly the U.S. dollar together with time, power to lure and well-being so they can follow. Oakleys can absorb the harmful sun's rays, the filter performance of international standards, and effectively block light, and filter out the scattering function with the beam. Whether you need to modify?? You to adjust to your sunglasses, that is filmed by a similar company, it could guarantee identical service quality, mixing style and practicality. If you wish wholesale sunglasses online purchase is an excellent choice. This is the fantastic way to compare different sunglasses provide them with the price of their articles, their brand of wholesalers and retailers.

    Reply
  • Things other people has been doing with regard to nike and furthermore the thing youshould do totally different.

    Posted by icoppyapedcap on 04/21/2013 08:11pm

    Hw [url=http://hunter-rain-boots.webnode.jp]ハンターレインブーツ[/url] bUi [url=http://hunterrainbootsjp.webnode.jp]ハンターレインブーツ[/url] k ExgNnc ZwrF [url=http://hunter-boots8.webnode.jp]レインブーツメンズ[/url] ug Q [url=http://rain-boots-men.webnode.jp]ハンター長靴[/url] jr [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツ[/url] CdqWjsVsw J[url=http://rainshoesja.webnode.jp]レインブーツ[/url] ueXrqStsHb [url=http://ja-hunter-rain-boots.webnode.jp]ハンターレインブーツ[/url] o GbvMzy [url=http://rain-boots-popular.webnode.jp]レインブーツ人気[/url] Vck [url=http://rain-boots-men6.webnode.jp]レインブーツハンター[/url] Rzo Exh [url=http://jahunterrainboots.webnode.jp]レインブーツメンズ[/url] Atb

    Reply
  • date without year

    Posted by hfr on 04/07/2005 03:25am

    Ist there a way to use only month and day like "m" or "M" where the month is displayed as number from 01 to 12 using the current culture?
    
    e.g. 1st decemnber
    01.12 (German)
    12/01 (English)
    
    ...even if the system information has set the short date format e.g. to mm/dd/yyyy
    
    Kind regards, hfr

    Reply
  • Daveloper

    Posted by kdpo1990 on 12/27/2004 06:12pm

    Thank you, Very good example Al

    Reply
  • Interesting article

    Posted by dwillms on 03/14/2004 04:57pm

    Interesting article.

    Reply
  • Q: Convert string to DateTime ???

    Posted by Legacy on 08/21/2003 12:00am

    Originally posted by: Yuri

    Hello,
    I have a little question.
    How can I convert the date string "dd/MM/yyyy" to the structure DateTime?
    I used DateTime.Pase method, but still have "String was not recognized as a valid DateTime"

    ...
    DateTime date = DateTime.Today;
    string strDate = "25/12/2003";
    date=DateTime.Parse(strDate);
    ...

    May be I have to initialize format? but I don't find how I can do that.

    Best regards
    Yuri

    • try this

      Posted by purohitrohit on 06/12/2006 08:49am

      MsgBox(DateTime.Today.ToString("dd/MMM/yyyy").ToUpper)

      Reply
    • problem with Format function

      Posted by johncaeser on 05/04/2004 11:31am

      There is a bug with the current framework. The format function works occasionally.This is been fixed in the Update. Use System globalization lib John

      Reply
    Reply
  • why the value of millisecond is zero?

    Posted by Legacy on 02/05/2003 12:00am

    Originally posted by: Rick

    I have a little code below, it's a part of my small C# program:
    
    

    startTime = System.DateTime.Now.Millisecond;
    label1.Text = startTime.ToString();

    Why each time I run the code in .NET, it always returns 0?

    Thanks.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds