C# DateTime Format String

Updated on 21 May 2012,
Published on 20 Feb 2008

In the previous article C# Function to Get Current DateTime in ASP.Net 2.0, you learnt how to get current date and its string formatting using

DateTime.Now.ToString("xxxxxxx")

To customize the format of date or time you can pass appropriate format string to ToString function.

Different types of Time formats that are commonly used in ASP.Net 2.0 are:

13:39:21.0363750

1:39 PM

13:39 21 PM

01:39 21 PM

1339

DateTime Format Examples:

You can see the live samples and examples of C# DateTime format from the following links:

C# Functions to format the server Time String

C# Time Formats
Example 1
Response.Write(DateTime.Now.TimeOfDay);
Output

13:39:21.0363750

Example 2
Response.Write(DateTime.Now.ToShortTimeString());
Output

1:39 PM 

Example 3
Response.Write(DateTime.Now.ToString("HH:mm ss tt"));
Output

13:39 21 PM

Note: To format the time in 24H format you can use the capital HH to display the hours, mm to display the minutes, ss to display the seconds and tt for AM/PM.

Example 4
Response.Write(DateTime.Now.ToString("hh:mm ss tt"));
Output

01:39 21 PM

Note: To format the time into short string type, you can use the lower case hh to display the hours.

Example 5
Response.Write(DateTime.Now.ToString("HHmm"));
Output

1339

Note:  To display the time in hours format, just use HHmm without separators.

Output:

You can see the outputs of above C# code from the following links:

Time Formats using ToString Function

Date Formats using ToString Function

Convert String to DateTime

Also learn from the tutorial: C# Date Format using ToString function to convert the Date value to specified Date format.

10 Responses to "C# DateTime Format String"
I have been looking for this formatting .ToString for 2 hours! Worked perfectly - Thanks
Dawg
Thanks for the article.
Thanks. I was looking from datetime functions in C#.
Patrick
Thank you - after searching for way too long (like John), I realize more and more why I stick to PHP like glue. Thanks for the help.
shaffy
Thanks for the article.
MarCowang
DateTime.Parse(TxtSo_Date.Text.Trim()).ToString(?)
how to output for example:
02 Novermber 2009
current Datetime is "2009/11/02"
Ezineasp.net
Hi MarCowang

You can learn about the C# DateTime Parse function from the following tutorial:
C# DateTime Parse Function

or you can also try the Convert.ToDateTime function as follows:

Convert.ToDateTime("2009/11/02").ToString("dd MMMM yyyy")

Output:
02 Novermber 2009

Hope this will help you. Good Luck.
asit
wonderfulllll thangs.
Virang
Perfect solution with perfect exaples. Thanks.
pruznejjoe
Works perfect, thanks
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email