C# date format and examples, with binding and ToString

Lionsure 2020-07-26 Original by the website

The date generally only outputs the year, month and day. Since the date is accurate to the second by default, only output the year, month and day to specify its output format. What are the commonly used output formats?

 

1. Format of binding date(C# date format)

When you want to bind a date-type field, how to output it? code show as below:

<%# Eval( "Date field"),"{0:MM/dd/yyyy}")%>

<asp:BoundColumn DataField="Date field"       HeaderText="Release date"  DataFormatString="{0:MM/dd/yyyy}">

Output result: For example, the date is 07/08/2020 10:15:28 AM, the final output is: 07/08/2020

 

2. Output with ToString()(C# date string format)

DateTime dt = DateTime.Now;
       dt.ToString("MM/dd/yyyy"); //Output: 07/26/2020
       dt.ToShortDateString().ToString(); //Output: 07/26/2020

dt.ToString("dddd, MMMM dd yyyy"); //Output: Sunday, July 26, 2020
       dt.ToLongDateString().ToString(); //Output: Sunday, July 26, 2020

dt.ToLongTimeString().ToString(); //Output: 11:05:07 AM

dt.Date.ToString(); //Output: 7/26/2020 12:00:00 AM
       dt.Year.ToString(); //Output: 2020
       dt.Month.ToString(); //Output: 7
       dt.Day.ToString(); //Output: 26

Others and so on.

 

3. C# date string formats(C sharp date formats)

d: Use the locale's short date format        Output: 07/08/2020
       D: Long date format according to regional settings       Output: Friday, 08 July 2020
       f: Full date and time(long date and short time)        Output: Friday, 08 July 2020 10:15
       F: FullDateTimePattern(Long date and long time)        Output: Friday, 08 July 2020 10:15:28

 

g: Regular(short date and short time)       Output: 07/08/2020 10:15
       G: Regular (short date and long time)        Output: 07/08/2020 10:15:28
       M or m: MonthDayPattern       Output: July 08

R or r: Format date and time as Greenwich Mean Time(GMT)       Output: Friday, 08 July 2020 10:15:28 GMT

s: Format date and time as sortable index(based on ISO 8601)       Output: 2020-07-08T10:15:28

 

t: ShortTimePattern       Output: 10:15
       T: LongTimePattern       Output: 10:15:28

u: UniversalSortableDateTimePattern format used to display universal time       Output: 2020-07-08 10:15:28Z

U: Full date and time using universal time(long date and long time)       Output: Friday, 08 July 2020 10:15:28

 

y or Y: YearMonthPattern       Output: 2020 July
       dddd, MMMM dd yyyy       Output: Friday, July 08 2020
       ddd, MMM d "'"yy         Output: Friday, Jul 08 '20
       dddd, MMMM dd       Output: Friday, July 08

 

For example:

<%# Eval("Date field"), "{0:d}")%> or DataFormatString="{0:d}"

DateTime dt = DateTime.Now;
       Response.Write(dt.ToString("ddd, MMM d \"'\"yy"));