terça-feira, 1 de fevereiro de 2011

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:
C# Code Example 1:
Response.Write(DateTime.Now.TimeOfDay);

Output: 13:39:21.0363750

C# Code Example 2:
Response.Write(DateTime.Now.ToShortTimeString());

Output: 1:39 PM

C# Code 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 hoursmm to display the minutesss to display theseconds and tt for AM/PM.

C# Code 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.

C# Code 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 functionto convert the Date value to specified Date format

Sem comentários:

Enviar um comentário