C# DateTime Format String
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
Also learn from the tutorial: C# Date Format using ToString function to convert the Date value to specified Date format.
