Sunteți pe pagina 1din 94

C# DateTime Format

String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done


also using DateTime.ToString method.

Custom DateTime Formatting


There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour
24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M
or A.M) and z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.

[C#]

// create date time 2008-03-09 16:05:07.123


DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year


String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten
to characters defined in the current DateTimeFormatInfo.DateSeparator andDateTimeForma-
tInfo.TimeSeparator.

[C#]

// date separator in german culture is "." (so "/" changes to ".")


String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:

[C#]

// month/day numbers without/with leading zeroes


String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting


In DateTimeFormatInfo there are defined standard patterns for the current culture. For example
property ShortTimePattern is string that contains value h:mm tt for en-US culture and
value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First
column contains format specifiers for the String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)


t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of  D and  t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of  d and  t) M/d/yyyy h:mm tt
G (combination of  d and  T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
ddd, dd MMM yyyy HH':'mm':'ss
r, R RFC1123Pattern
'GMT' (*)
s SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
    (*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting
output.

[C#]

String.Format("{0:t}", dt); // "4:05 PM" ShortTime


String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z"
UniversalSortableDateTime

========================
You need help with DateTime format strings in the C# language or
other .NET languages. The framework provides powerful formatting
capabilities, but the syntax is confusing and there are some tricks. Here
we see examples of using DateTime formats, and also the different
values you can get with the individual formats.

Format your DateTimes for your application.


You will not have to write elaborate custom routines.
The .NET Framework has a powerful DateTime format
mechanism.

DateTime format string


Here we see an example of how you can use a specific formatting string
with DateTime and ToString to obtain a special DateTime string. This is
useful when interacting with other systems, or when you require a
precise format.

=== Program that uses DateTime format [C#] ===

using System;

class Program

static void Main()

DateTime time = DateTime.Now; // Use current time

string format = "MMM ddd d HH:mm yyyy"; // Use this format

Console.WriteLine(time.ToString(format)); // Write to console

=== Output of the program ===


Feb Fri 27 11:41 2009

=== Format string pattern ===

MMM display three-letter month

ddd display three-letter day of the WEEK

d display day of the MONTH

HH display two-digit hours on 24-hour scale

mm display two-digit minutes

yyyy display four-digit year

Notes on the letters. The letters in the format string above specify


the output you want to display. The final comment shows what the
MMM, ddd, d, HH, mm, and yyyy will do.

Modify format
Here we see how you can modify the DateTime format string in the
above example to get different output with ToString. We change some
of the fields so the resulting value is shorter.

=== Program that uses different format [C#] ===

using System;

class Program

static void Main()

DateTime time = DateTime.Now; // Use current time

string format = "M d h:mm yy"; // Use this format

Console.WriteLine(time.ToString(format)); // Write to console


}

=== Output of the program ===

2 27 11:48 09

=== Format string pattern ===

M display one-digit month number [changed]

d display one-digit day of the MONTH [changed]

h display one-digit hour on 12-hour scale [changed]

mm display two-digit minutes

yy display two-digit year [changed]

Note on format string usages. You will also need to specify a format


string when using DateTime.ParseExact and DateTime.ParseExact. This
is because those methods require a custom pattern to parse.

Single-letter format
Here we see that you can use a single character with ToString or
DateTime.ParseExact to specify a preset format available in the
framework. These are standard formats and very useful in many
programs. They can eliminate typos in the custom format strings.

=== Program that tests formats [C#] ===

using System;

class Program

static void Main()


{

DateTime now = DateTime.Now;

Console.WriteLine(now.ToString("d"));

Console.WriteLine(now.ToString("D"));

Console.WriteLine(now.ToString("f"));

Console.WriteLine(now.ToString("F"));

Console.WriteLine(now.ToString("g"));

Console.WriteLine(now.ToString("G"));

Console.WriteLine(now.ToString("m"));

Console.WriteLine(now.ToString("M"));

Console.WriteLine(now.ToString("o"));

Console.WriteLine(now.ToString("O"));

Console.WriteLine(now.ToString("s"));

Console.WriteLine(now.ToString("t"));

Console.WriteLine(now.ToString("T"));

Console.WriteLine(now.ToString("u"));

Console.WriteLine(now.ToString("U"));

Console.WriteLine(now.ToString("y"));

Console.WriteLine(now.ToString("Y"));

=== Output of the program ===

d 2/27/2009

D Friday, February 27, 2009

f Friday, February 27, 2009 12:11 PM


F Friday, February 27, 2009 12:12:22 PM

g 2/27/2009 12:12 PM

G 2/27/2009 12:12:22 PM

m February 27

M February 27

o 2009-02-27T12:12:22.1020000-08:00

O 2009-02-27T12:12:22.1020000-08:00

s 2009-02-27T12:12:22

t 12:12 PM

T 12:12:22 PM

u 2009-02-27 12:12:22Z

U Friday, February 27, 2009 8:12:22 PM

y February, 2009

Y February, 2009

Date strings
Here we see the ToLongDateString, ToLongTimeString,
ToShortDateString, and ToShortTimeString methods on DateTime.
These methods are equivalent to the lowercase and uppercase D and T
methods shown in the example above.

=== Program that uses ToString methods [C#] ===

using System;

class Program

static void Main()

DateTime now = DateTime.Now;


Console.WriteLine(now.ToLongDateString()); // Equivalent to D

Console.WriteLine(now.ToLongTimeString()); // Equivalent to T

Console.WriteLine(now.ToShortDateString()); // Equivalent to d

Console.WriteLine(now.ToShortTimeString()); // Equivalent to t

Console.WriteLine(now.ToString());

=== Output of the program ===

ToLongDateString Friday, February 27, 2009

ToLongTimeString 12:16:59 PM

ToShortDateString 2/27/2009

ToShortTimeString 12:16 PM

ToString 2/27/2009 12:16:59 PM

Note on default ToString method. The default ToString method on


DateTime shown above is equivalent to the simple "G" formatting string
in the previous example. In other words, ToString("G") and ToString()
do the same thing.

Format characters
When you use DateTime.ParseExact, or ToString(), you need to specify
a formatting string, which is a sequence of characters that designate
how the final result will look. What follows are my notes on the strings
from MSDN.

See 24-Hour and Military Time Formats.

d
Use this to specify the numeric value for the day of the month.
It will be one or two digits long.

dd
This is the same as a single d, except there are always two
digits, with a leading 0 prepended if necessary.

ddd
This displays a three-letter string that indicates the current day
of the week.

dddd
This displays the full string for the day of the week.

f
ff
fff
ffff
fffff
ffffff
fffffff
F
FF
FFF
FFFF
FFFFF
FFFFFF
FFFFFFF
Use the lowercase f to indicate the seconds to one digit length.
Use two lowercase fs to indicate the seconds to two digits. The
uppercase F patterns do the same but work differently on
trailing zeros.

gg
Use this to display A.D. on your date. It is unlikely that this will
be B.C. in most programs.

h
Display the hours in one digit if possible. If the hours is greater
than 9, it will display two digits. Range is 1-12.

hh
Display the hours in two digits always, even if the hour is one
digit. The range here will be 01-12.
H
This represents the hours in a range of 0-23, which is called
military time in some parts of the world.

HH
This represents the hours in a range of 00-23. The only
different here between the single H is that there is always a
leading zero if the number is one digit.

K
Use this to display time zone information.

m
mm
This formats the minutes in your date format string. Here, the
one m means that there is only one digit displayed if possible.
The two ms means that there are always two digits displayed,
with a leading zero if necessary.

M
MM
These display the months in numeric form. The one uppercase
M does not have a leading zero on it. The two uppercase Ms
will format a number with a leading zero if it is required.

MMM
This displays the abbreviated three-letter form of the month
represented in the DateTime.

MMMM
This displays the full month string, properly capitalized.

s
ss
The lowercase s displays seconds. A single lowercase s means
that you do not require a leading zero. Two lowercase s
characters means you always want two digits, such as 00-59.

t
Use the lowercase t to indicate A, when the time is in the AM,
and P, for when the time is in PM.

tt
Use two lowercase tts to display the full AM or PM string. You
will normally want this for when you are displaying the string to
a user.

y
yy
yyy
yyyy
yyyyy
These display the year to different digits. In your programs,
you won't need three digits for the year, or five. Therefore, you
should only consider one y, two ys, or four ys.

z
zz
zzz
These represent the offset from the UTC time on the local
operating system.

:
This is the time separator.

/
This is the date separator.

Difference between d and dd, ddd and dddd. It is important to note


that d and dd (one and two ds) mean something entirely different than
ddd and dddd (three and four ds). d and dd indicate the day of the
month, while ddd and dddd indicate the day of the week, in a word.

Three-letter days
In some systems it may be useful to display the day of the week in a
three-letter form. Here we see a simple program that prints out the
days of the week in three-letter format. This will vary based on the
language installed on the computer.

=== Program that tests days [C#] ===


using System;

class Program

static void Main()

DateTime now = DateTime.Today;

for (int i = 0; i < 7; i++)

Console.WriteLine(now.ToString("ddd"));

now = now.AddDays(1);

=== Output of the program ===

Thu

Fri

Sat

Sun

Mon

Tue

Wed

Display complete day


Often you need to display the complete day of the week in your C#
code, and the four ds together will do this for you. This simple program
shows all seven different day strings you can get from the dddd.
=== Program that shows day strings [C#] ===

using System;

class Program

static void Main()

DateTime now = DateTime.Today;

for (int i = 0; i < 7; i++)

Console.WriteLine(now.ToString("dddd"));

now = now.AddDays(1);

=== Output of the program ===

Thursday

Friday

Saturday

Sunday

Monday

Tuesday

Wednesday
Display the era
The .NET platform allows you to display the date with the era or period,
which is usually A.D. or B.C. It is unlikely that you will need to use B.C.,
except in a rare theoretical application. Nevertheless, here is what the
two gs will print. Use the code "DateTime.Now.ToString("gg");".

Month format
You may need to display the month name in a three-letter format. This
is equivalent, in English, to taking a substring of the first three letters,
but using the three Ms next to each other may be easier and more terse
for your code. Additionally, you may want full month strings. This site
contains a useful article that covers DateTime month strings and the
Month property in more detail.

See DateTime.Month Property.

Display AM/PM
This isn't something you are likely to need, but interesting to find out.
When you specify one t, you can get the first letter of the AM or PM
string. This is equivalent to using Substring or getting the first char of
the tt string. There is a space at the end of the format string because
the value "t" can mean something else in the format string.

Full string. Here we see how you can get the string AM or PM in your
DateTime ToString code. The code adds 12 to ensure the second
iteration is in the other half.

=== Program that displays AM and PM [C#] ===

using System;

class Program

static void Main()

DateTime now = DateTime.Now;

for (int i = 0; i < 2; i++)


{

Console.WriteLine(now.ToString("tt "));

now = now.AddHours(12);

=== Output of the program ===

PM

AM

Note on lack of periods. There are no periods in the output of tt in


the example above. Therefore, if you require periods in your AM or PM,
you would have to manipulate the string.

Display year
You can vary the number of digits displayed in the year string. You will
always want to use y, yy, or yyyy for your programs. The framework
accepts different numbers, but they are impractical in the real world.
Occasionally two ys is useful for a user-oriented program, but for your
back end code, you will want to use four ys. You do not need uppercase
Ys.

=== Program that displays years [C#] ===

using System;

class Program

static void Main()

{
DateTime now = DateTime.Now;

Console.WriteLine(now.ToString("y "));

Console.WriteLine(now.ToString("yy"));

Console.WriteLine(now.ToString("yyy")); // <-- Don't use this

Console.WriteLine(now.ToString("yyyy"));

Console.WriteLine(now.ToString("yyyyy")); // <-- Don't use this

=== Output of the program ===

09

2009

2009

02009

Standard Date and Time Format Strings


.NET Framework 4

Other Versions

Updated: July 2010


A standard date and time format string uses a single format specifier to define the text representation of a date
and time value. Any date and time format string that contains more than one character, including white space, is
interpreted as a custom date and time format string; for more information, see Custom Date and Time Format
Strings. A standard or custom format string can be used in two ways:
• To define the string that results from a formatting operation.
• To define the text representation of a date and time value that can be converted to
a DateTime or DateTimeOffset value by a parsing operation.
Note
Standard date and time format strings can be used with
both DateTime and DateTimeOffset values.
The following table describes the standard date and time format specifiers. Unless otherwise noted,
a particular standard date and time format specifier produces an identical string representation
regardless of whether it is used with a DateTime or a DateTimeOffset value. See the Notes section
for additional information about using standard date and time format strings.
Format
Description Examples
specifier

6/15/2009 1:45:30 PM -> 6/15/2009 (en-


US)
Short date pattern.
6/15/2009 1:45:30 PM -> 15/06/2009 (fr-
"d" More information: The Short Date
FR)
("d") Format Specifier.
6/15/2009 1:45:30 PM -> 2009/06/15 (ja-
JP)
6/15/2009 1:45:30 PM -> Monday, June 15,
2009 (en-US)
Long date pattern.
6/15/2009 1:45:30 PM -> 15 июня 2009 г.
"D" More information: The Long Date
(ru-RU)
("D") Format Specifier.
6/15/2009 1:45:30 PM -> Montag, 15. Juni
2009 (de-DE)
6/15/2009 1:45:30 PM -> Monday, June 15,
2009 1:45 PM (en-US)
Full date/time pattern (short time).
6/15/2009 1:45:30 PM -> den 15 juni 2009
"f" More information: The Full Date
13:45 (sv-SE)
Short Time ("f") Format Specifier.
6/15/2009 1:45:30 PM -> Δευτέρα, 15
Ιουνίου 2009 1:45 μμ (el-GR)
6/15/2009 1:45:30 PM -> Monday, June 15,
2009 1:45:30 PM (en-US)
Full date/time pattern (long time).
6/15/2009 1:45:30 PM -> den 15 juni 2009
"F" More information: The Full Date
13:45:30 (sv-SE)
Long Time ("F") Format Specifier.
6/15/2009 1:45:30 PM -> Δευτέρα, 15
Ιουνίου 2009 1:45:30 μμ (el-GR)
6/15/2009 1:45:30 PM -> 6/15/2009 1:45
General date/time pattern (short PM (en-US)
time). 6/15/2009 1:45:30 PM -> 15/06/2009 13:45
"g"
More information: The General Date (es-ES)
Short Time ("g") Format Specifier. 6/15/2009 1:45:30 PM -> 2009/6/15 13:45
(zh-CN)
6/15/2009 1:45:30 PM -> 6/15/2009
General date/time pattern (long 1:45:30 PM (en-US)
time). 6/15/2009 1:45:30 PM -> 15/06/2009
"G"
More information: The General Date 13:45:30 (es-ES)
Long Time ("G") Format Specifier. 6/15/2009 1:45:30 PM -> 2009/6/15
13:45:30 (zh-CN)
"M", "m" Month/day pattern. 6/15/2009 1:45:30 PM -> June 15 (en-US)
More information: The Month ("M", 6/15/2009 1:45:30 PM -> 15. juni (da-DK)
"m") Format Specifier. 6/15/2009 1:45:30 PM -> 15 Juni (id-ID)
Round-trip date/time pattern.
6/15/2009 1:45:30 PM -> 2009-06-
"O", "o" More information: The Round-trip
15T13:45:30.0900000
("O", "o") Format Specifier.
RFC1123 pattern.
6/15/2009 1:45:30 PM -> Mon, 15 Jun 2009
"R", "r" More information: The RFC1123
20:45:30 GMT
("R", "r") Format Specifier.
Sortable date/time pattern.
6/15/2009 1:45:30 PM -> 2009-06-
"s" More information: The Sortable
15T13:45:30
("s") Format Specifier.
Short time pattern. 6/15/2009 1:45:30 PM -> 1:45 PM (en-US)
"t" More information: The Short Time 6/15/2009 1:45:30 PM -> 13:45 (hr-HR)
("t") Format Specifier. 6/15/2009 1:45:30 PM -> 01:45 ‫( م‬ar-EG)
6/15/2009 1:45:30 PM -> 1:45:30 PM (en-
Long time pattern. US)
"T" More information: The Long Time 6/15/2009 1:45:30 PM -> 13:45:30 (hr-HR)
("T") Format Specifier. 6/15/2009 1:45:30 PM -> 01:45:30 ‫( م‬ar-
EG)
Universal sortable date/time pattern.
6/15/2009 1:45:30 PM -> 2009-06-15
"u" More information: The Universal
20:45:30Z
Sortable ("u") Format Specifier.
6/15/2009 1:45:30 PM -> Monday, June 15,
2009 8:45:30 PM (en-US)
Universal full date/time pattern.
6/15/2009 1:45:30 PM -> den 15 juni 2009
"U" More information: The Universal
20:45:30 (sv-SE)
Full ("U") Format Specifier.
6/15/2009 1:45:30 PM -> Δευτέρα, 15
Ιουνίου 2009 8:45:30 μμ (el-GR)
6/15/2009 1:45:30 PM -> June, 2009 (en-
Year month pattern. US)
"Y", "y" More information: The Year Month 6/15/2009 1:45:30 PM -> juni 2009 (da-
("Y") Format Specifier. DK)
6/15/2009 1:45:30 PM -> Juni 2009 (id-ID)
Any other
Unknown specifier. Throws a run-time FormatException.
single character

How Standard Format Strings Work

In a formatting operation, a standard format string is simply an alias for a custom format string. The
advantage of using an alias to refer to a custom format string is that, although the alias remains
invariant, the custom format string itself can vary. This is important because the string
representations of date and time values typically vary by culture. For example, the "d" standard
format string indicates that a date and time value is to be displayed using a short date pattern. For
the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For
the ja-JP culture, it is "yyyy/MM/dd".
If a standard format string in a formatting operation maps to a particular culture's custom format string, your
application can define the specific culture whose custom format strings are used in one of these ways:
• You can use the default (or current) culture. The following example displays a date using the current
culture's short date format. In this case, the current culture is en-US.
VB
C#
C++
F#
JScript
Copy

// Display using current (en-us) culture's short date format


DateTime thisDate = new DateTime(2008, 3, 15);
Console.WriteLine(thisDate.ToString("d")); // Displays 3/15/2008

• You can pass a CultureInfo object representing the culture whose formatting is to be used to a method
that has an IFormatProvider parameter. The following example displays a date using the short date
format of the pt-BR culture.
VB
C#
C++
F#
JScript
Copy

// Display using pt-BR culture's short date format


DateTime thisDate = new DateTime(2008, 3, 15);
CultureInfo culture = new CultureInfo("pt-BR");
Console.WriteLine(thisDate.ToString("d", culture)); // Displays 15/3/2008

• You can pass a DateTimeFormatInfo object that provides formatting information to a method that has
an IFormatProvider parameter. The following example displays a date using the short date format from
a DateTimeFormatInfo object for the hr-HR culture.
VB
C#
C++
F#
JScript
Copy

// Display using date format information from hr-HR culture


DateTime thisDate = new DateTime(2008, 3, 15);
DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat;
Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008

In some cases, the standard format string serves as a convenient abbreviation for a longer custom format string
that is invariant. Four standard format strings fall into this category: "O" (or "o"), "R" (or "r"), "s", and "u". These
strings correspond to custom format strings defined by the invariant culture. They produce string
representations of date and time values that are intended to be identical across cultures. The following table
provides information on these four standard date and time format strings.
Standard format Defined by DateTimeFormatInfo.InvariantInfo
Custom format string
string property

yyyy'-'MM'-'dd'T'HH':'mm'
"O" or "o" None
:'ss'.'fffffffzz
ddd, dd MMM yyyy
"R" or "r" RFC1123Pattern
HH':'mm':'ss 'GMT'
yyyy'-'MM'-'dd'T'HH':'mm'
"s" SortableDateTimePattern
:'ss
yyyy'-'MM'-'dd
"u" UniversalSortableDateTimePattern
HH':'mm':'ss'Z'
Standard format strings can also be used in parsing operations with
the DateTime.ParseExact or DateTimeOffset.ParseExact methods, which require an input string to exactly
conform to a particular pattern for the parse operation to succeed. Many standard format strings map to
multiple custom format strings, so a date and time value can be represented in a variety of formats and the
parse operation will still succeed. You can determine the custom format string or strings that correspond to a
standard format string by calling the DateTimeFormatInfo.GetAllDateTimePatterns(Char) method. The following
example displays the custom format strings that map to the "d" (short date pattern) standard format string.
VB
C#
C++
F#
JScript
Copy

using System;
using System.Globalization;

public class Example


{
public static void Main()
{
Console.WriteLine("'d' standard format string:");
foreach (var customString in
DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d'))
Console.WriteLine(" {0}", customString);
}
}
// The example displays the following output:
// 'd' standard format string:
// M/d/yyyy
// M/d/yy
// MM/dd/yy
// MM/dd/yyyy
// yy/MM/dd
// yyyy-MM-dd
// dd-MMM-yy

The following sections describe the standard format specifiers for DateTime and DateTimeOffset values.

The Short Date ("d") Format Specifier


The "d" standard format specifier represents a custom date and time format string that is defined by
a specific culture's DateTimeFormatInfo.ShortDatePattern property. For example, the custom
format string that is returned by the ShortDatePattern property of the invariant culture is
"MM/dd/yyyy".
The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned
string.

Property Description

ShortDatePattern Defines the overall format of the result string.


Defines the string that separates the year, month, and day components of a
DateSeparator
date.
The following example uses the "d" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008,4, 10);


Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008
Console.WriteLine(date1.ToString("d",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays 4/10/2008
Console.WriteLine(date1.ToString("d",
CultureInfo.CreateSpecificCulture("en-NZ")));
// Displays 10/04/2008
Console.WriteLine(date1.ToString("d",
CultureInfo.CreateSpecificCulture("de-DE")));
// Displays 10.04.2008

Back to table

The Long Date ("D") Format Specifier

The "D" standard format specifier represents a custom date and time format string that is defined by
the current DateTimeFormatInfo.LongDatePattern property. For example, the custom format string
for the invariant culture is "dddd, dd MMMM yyyy".
The following table lists the properties of the DateTimeFormatInfo object that control the formatting of the
returned string.

Property Description

LongDatePattern Defines the overall format of the result string.


DayNames Defines the localized day names that can appear in the result string.
Defines the localized month names that can appear in the result
MonthNames
string.
The following example uses the "D" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10);


Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008
Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("pt-BR")));
// Displays quinta-feira, 10 de abril de 2008
Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("es-MX")));
// Displays jueves, 10 de abril de 2008

Back to table

The Full Date Short Time ("f") Format Specifier

The "f" standard format specifier represents a combination of the long date ("D") and short time
("t") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The
following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned
string. The custom format specifier returned by
the DateTimeFormatInfo.LongDatePattern and DateTimeFormatInfo.ShortTimePatternproperties of some
cultures may not make use of all properties.

Property Description

LongDatePattern Defines the format of the date component of the result string.
ShortTimePattern Defines the format of the time component of the result string.
DayNames Defines the localized day names that can appear in the result string.
MonthNames Defines the localized month names that can appear in the result string.
Defines the string that separates the hour, minute, and second components of a
TimeSeparator
time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "f" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("f",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 6:30 AM
Console.WriteLine(date1.ToString("f",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays jeudi 10 avril 2008 06:30

Back to table

The Full Date Long Time ("F") Format Specifier

The "F" standard format specifier represents a custom date and time format string that is defined by
the current DateTimeFormatInfo.FullDateTimePattern property. For example, the custom format
string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".
The following table lists the DateTimeFormatInfo object properties that may control the formatting of the
returned string. The custom format specifier that is returned by theFullDateTimePattern property of some
cultures may not make use of all properties.

Property Description

FullDateTimePattern Defines the overall format of the result string.


DayNames Defines the localized day names that can appear in the result string.
MonthNames Defines the localized month names that can appear in the result string.
Defines the string that separates the hour, minute, and second components of
TimeSeparator
a time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "F" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("F",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 6:30:00 AM
Console.WriteLine(date1.ToString("F",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays jeudi 10 avril 2008 06:30:00
Back to table

The General Date Short Time ("g") Format Specifier

The "g" standard format specifier represents a combination of the short date ("d") and short time
("t") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The
following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned
string. The custom format specifier that is returned by
the DateTimeFormatInfo.ShortDatePattern andDateTimeFormatInfo.ShortTimePattern properties of some
cultures may not make use of all properties.

Property Description

ShortDatePattern Defines the format of the date component of the result string.
ShortTimePattern Defines the format of the time component of the result string.
DateSeparator Defines the string that separates the year, month, and day components of a date.
Defines the string that separates the hour, minute, and second components of a
TimeSeparator
time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "g" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("g",
DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30
Console.WriteLine(date1.ToString("g",
CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30 AM
Console.WriteLine(date1.ToString("g",
CultureInfo.CreateSpecificCulture("fr-BE")));
// Displays 10/04/2008 6:30

Back to table

The General Date Long Time ("G") Format Specifier


The "G" standard format specifier represents a combination of the short date ("d") and long time
("T") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The
following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned
string. The custom format specifier that is returned by
the DateTimeFormatInfo.ShortDatePattern andDateTimeFormatInfo.LongTimePattern properties of some
cultures may not make use of all properties.

Property Description

ShortDatePattern Defines the format of the date component of the result string.
LongTimePattern Defines the format of the time component of the result string.
DateSeparator Defines the string that separates the year, month, and day components of a date.
Defines the string that separates the hour, minute, and second components of a
TimeSeparator
time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "G" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("G",
DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G",
CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM
Console.WriteLine(date1.ToString("G",
CultureInfo.CreateSpecificCulture("nl-BE")));
// Displays 10/04/2008 6:30:00

Back to table

The Month ("M", "m") Format Specifier

The "M" or "m" standard format specifier represents a custom date and time format string that is
defined by the current DateTimeFormatInfo.MonthDayPattern property. For example, the custom
format string for the invariant culture is "MMMM dd".
The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned
string.

Property Description
MonthDayPattern Defines the overall format of the result string.
Defines the localized month names that can appear in the result
MonthNames
string.
The following example uses the "m" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("m",
CultureInfo.CreateSpecificCulture("en-us")));
// Displays April 10
Console.WriteLine(date1.ToString("m",
CultureInfo.CreateSpecificCulture("ms-MY")));
// Displays 10 April

Back to table

The Round-trip ("O", "o") Format Specifier

The "O" or "o" standard format specifier represents a custom date and time format string using a
pattern that preserves time zone information. For DateTime values, this format specifier is designed
to preserve date and time values along with the DateTime.Kind property in text. The formatted
string can be parsed back by using theDateTime.Parse(String, IFormatProvider,
DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set
to DateTimeStyles.RoundtripKind.
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom
format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string
for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters,
such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot
be changed. The apostrophes do not appear in the output string.
The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of
the culture used or the format provider supplied. Strings that are passed to the Parse or ParseExact method
must conform exactly to this custom format pattern, or a FormatException is thrown.
When this standard format specifier is used, the formatting or parsing operation always uses the invariant
culture.
The following example uses the "o" format specifier to display a DateTime and a DateTimeOffset value on a
system in the U.S. Pacific Time zone.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


DateTimeOffset dateOffset = new DateTimeOffset(date1,
TimeZoneInfo.Local.GetUtcOffset(date1));
Console.WriteLine(date1.ToString("o"));
// Displays 2008-04-10T06:30:00.0000000
Console.WriteLine(dateOffset.ToString("o"));
// Displays 2008-04-10T06:30:00.0000000-07:00

The following example uses the "o" format specifier to create a formatted string, and then restores the original
date and time value by calling a date and time Parse method.
VB
C#
C++
F#
JScript
Copy

// Round-trip DateTime values.


DateTime originalDate, newDate;
string dateString;
// Round-trip a local time.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 10, 6, 30, 0),
DateTimeKind.Local);
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind,
newDate, newDate.Kind);
// Round-trip a UTC time.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 12, 9, 30, 0),
DateTimeKind.Utc);
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind,
newDate, newDate.Kind);
// Round-trip time in an unspecified time zone.
originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 13, 12, 30, 0),
DateTimeKind.Unspecified);
dateString = originalDate.ToString("o");
newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind,
newDate, newDate.Kind);

// Round-trip a DateTimeOffset value.


DateTimeOffset originalDTO = new DateTimeOffset(2008, 4, 12, 9, 30, 0, new TimeSpan(-8,
0, 0));
dateString = originalDTO.ToString("o");
DateTimeOffset newDTO = DateTimeOffset.Parse(dateString, null,
DateTimeStyles.RoundtripKind);
Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO);
// The example displays the following output:
// Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local.
// Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc.
// Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM
Unspecified.
// Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00.

Back to table
The RFC1123 ("R", "r") Format Specifier

The "R" or "r" standard format specifier represents a custom date and time format string that is
defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined
standard, and the property is read-only. Therefore, it is always the same, regardless of the culture
used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy
HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing
operation always uses the invariant culture.
The result string is affected by the following properties of the DateTimeFormatInfo object returned by
the DateTimeFormatInfo.InvariantInfo property that represents the invariant culture.

Property Description

RFC1123Pattern Defines the format of the result string.


AbbreviatedDayNames Defines the abbreviated day names that can appear in the result string.
Defines the abbreviated month names that can appear in the result
AbbreviatedMonthNames
string.
Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting
operation does not modify the value of the DateTime or DateTimeOffsetobject that is being formatted.
Therefore, the application must convert the date and time value to UTC before it performs the formatting
operation. To perform this conversion,DateTime values can call the DateTime.ToUniversalTime method,
and DateTimeOffset values can call the ToUniversalTime method.
The following example uses the "r" format specifier to display a DateTime and a DateTimeOffset value on a
system in the U.S. Pacific Time zone.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


DateTimeOffset dateOffset = new DateTimeOffset(date1,
TimeZoneInfo.Local.GetUtcOffset(date1));
Console.WriteLine(date1.ToUniversalTime().ToString("r"));
// Displays Thu, 10 Apr 2008 13:30:00 GMT
Console.WriteLine(dateOffset.ToUniversalTime().ToString("r"));
// Displays Thu, 10 Apr 2008 13:30:00 GMT

Back to table

The Sortable ("s") Format Specifier

The "s" standard format specifier represents a custom date and time format string that is defined by
the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard
(ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture
used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".
When this standard format specifier is used, the formatting or parsing operation always uses the invariant
culture.
The following example uses the "s" format specifier to display a DateTime and a DateTimeOffset value on a
system in the U.S. Pacific Time zone.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("s"));
// Displays 2008-04-10T06:30:00

Back to table

The Short Time ("t") Format Specifier

The "t" standard format specifier represents a custom date and time format string that is defined by
the current DateTimeFormatInfo.ShortTimePattern property. For example, the custom format string
for the invariant culture is "HH:mm".
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The
following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned
string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortTimePattern property of
some cultures may not make use of all properties.

Property Description

ShortTimePattern Defines the format of the time component of the result string.
Defines the string that separates the hour, minute, and second components of a
TimeSeparator
time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "t" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("t",
CultureInfo.CreateSpecificCulture("en-us")));
// Displays 6:30 AM
Console.WriteLine(date1.ToString("t",
CultureInfo.CreateSpecificCulture("es-ES")));
// Displays 6:30

Back to table

The Long Time ("T") Format Specifier

The "T" standard format specifier represents a custom date and time format string that is defined by
a specific culture's DateTimeFormatInfo.LongTimePattern property. For example, the custom
format string for the invariant culture is "HH:mm:ss".
The following table lists the DateTimeFormatInfo object properties that may control the formatting of the
returned string. The custom format specifier that is returned by
theDateTimeFormatInfo.LongTimePattern property of some cultures may not make use of all properties.

Property Description

LongTimePattern Defines the format of the time component of the result string.
Defines the string that separates the hour, minute, and second components of a
TimeSeparator
time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The following example uses the "T" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("T",
CultureInfo.CreateSpecificCulture("en-us")));
// Displays 6:30:00 AM
Console.WriteLine(date1.ToString("T",
CultureInfo.CreateSpecificCulture("es-ES")));
// Displays 6:30:00

Back to table

The Universal Sortable ("u") Format Specifier


The "u" standard format specifier represents a custom date and time format string that is defined by
the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined
standard, and the property is read-only. Therefore, it is always the same, regardless of the culture
used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".
When this standard format specifier is used, the formatting or parsing operation always uses the
invariant culture.
Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the
original DateTime or DateTimeOffset value is performed during the formatting operation. Therefore, the
application must convert the date and time value to UTC before formatting it. To perform this
conversion, DateTime values can call theDateTime.ToUniversalTime method, and DateTimeOffset values can call
the ToUniversalTime method
The following example uses the "u" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToUniversalTime().ToString("u"));
// Displays 2008-04-10 13:30:00Z

Back to table

The Universal Full ("U") Format Specifier

The "U" standard format specifier represents a custom date and time format string that is defined by
a specified culture's DateTimeFormatInfo.FullDateTimePattern property. The pattern is the same as
the "F" pattern. However, the DateTime value is automatically converted to UTC before it is
formatted.
The following table lists the DateTimeFormatInfo object properties that may control the formatting of the
returned string. The custom format specifier that is returned by theFullDateTimePattern property of some
cultures may not make use of all properties.

Property Description

FullDateTimePattern Defines the overall format of the result string.


DayNames Defines the localized day names that can appear in the result string.
MonthNames Defines the localized month names that can appear in the result string.
Defines the string that separates the hour, minute, and second components of
TimeSeparator
a time.
Defines the string that indicates times from midnight to before noon in a 12-
AMDesignator
hour clock.
Defines the string that indicates times from noon to before midnight in a 12-
PMDesignator
hour clock.
The "U" format specifier is not supported by the DateTimeOffset type and throws a FormatException if it is used
to format a DateTimeOffset value.
The following example uses the "U" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("U",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008 1:30:00 PM
Console.WriteLine(date1.ToString("U",
CultureInfo.CreateSpecificCulture("sv-FI")));
// Displays den 10 april 2008 13:30:00

Back to table

The Year Month ("Y", "y") Format Specifier

The "Y" or "y" standard format specifier represents a custom date and time format string that is
defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For
example, the custom format string for the invariant culture is "yyyy MMMM".
The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned
string.

Property Description

YearMonthPattern Defines the overall format of the result string.


Defines the localized month names that can appear in the result
MonthNames
string.
The following example uses the "y" format specifier to display a date and time value.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);


Console.WriteLine(date1.ToString("Y",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays April, 2008
Console.WriteLine(date1.ToString("y",
CultureInfo.CreateSpecificCulture("af-ZA")));
// Displays April 2008

Back to table

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:
• Time Formats using ToString Function
• Date Formats using ToString Function
• Convert String to DateTime
• DateTime Parse and ParseExact using IFormatProvider

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 hours, mm to
display the minutes, ss 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.

.NET Framework 4
Other Versions

Represents an instant in time, typically expressed as a date and time of day.


Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

VB
C#
C++
F#
JScript
Copy

[SerializableAttribute]
public struct DateTime : IComparable, IFormattable,
IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
The DateTime type exposes the following members.

Constructors

  Name Description
Initializes a new instance of the DateTime structure to a
  DateTime(Int64)
specified number of ticks.
Initializes a new instance of the DateTime structure to a
DateTime(Int64,
  specified number of ticks and to Coordinated Universal Time
DateTimeKind)
(UTC) or local time.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
 
Int32) specified year, month, and day.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
 
Int32, Calendar) specified year, month, and day for the specified calendar.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
 
Int32, Int32, Int32, Int32) specified year, month, day, hour, minute, and second.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
  Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, second, and
DateTimeKind) Coordinated Universal Time (UTC) or local time.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
  Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, and second for the
Calendar) specified calendar.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
  Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, second, and
Int32) millisecond.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
  Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, second, millisecond,
Int32, DateTimeKind) and Coordinated Universal Time (UTC) or local time.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
  Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, second, and
Int32, Calendar) millisecond for the specified calendar.
DateTime(Int32, Int32, Initializes a new instance of the DateTime structure to the
Int32, Int32, Int32, Int32, specified year, month, day, hour, minute, second, millisecond,
 
Int32, Calendar, and Coordinated Universal Time (UTC) or local time for the
DateTimeKind) specified calendar.
Top

Properties

  Name Description
  Date Gets the date component of this instance.
  Day Gets the day of the month represented by this instance.
  DayOfWeek Gets the day of the week represented by this instance.
  DayOfYear Gets the day of the year represented by this instance.
  Hour Gets the hour component of the date represented by this instance.
Gets a value that indicates whether the time represented by this instance is
  Kind
based on local time, Coordinated Universal Time (UTC), or neither.
  Millisecond Gets the milliseconds component of the date represented by this instance.
  Minute Gets the minute component of the date represented by this instance.
  Month Gets the month component of the date represented by this instance.
Gets a DateTime object that is set to the current date and time on this
    Now
computer, expressed as the local time.
  Second Gets the seconds component of the date represented by this instance.
  Ticks Gets the number of ticks that represent the date and time of this instance.
  TimeOfDay Gets the time of day for this instance.
    Today Gets the current date.
Gets a DateTime object that is set to the current date and time on this
    UtcNow
computer, expressed as the Coordinated Universal Time (UTC).
  Year Gets the year component of the date represented by this instance.
Top

Methods
  Name Description
Returns a new DateTime that adds the value of the
  Add
specified TimeSpan to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddDays
days to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddHours
hours to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddMilliseconds
milliseconds to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddMinutes
minutes to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddMonths
months to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddSeconds
seconds to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddTicks
ticks to the value of this instance.
Returns a new DateTime that adds the specified number of
  AddYears
years to the value of this instance.
Compares two instances of DateTime and returns an integer
    Compare that indicates whether the first instance is earlier than, the same
as, or later than the second instance.
Compares the value of this instance to a
specified DateTime value and returns an integer that indicates
  CompareTo(DateTime)
whether this instance is earlier than, the same as, or later than
the specified DateTime value.
Compares the value of this instance to a specified object that
contains a specified DateTime value, and returns an integer
  CompareTo(Object)
that indicates whether this instance is earlier than, the same as,
or later than the specified DateTime value.
    DaysInMonth Returns the number of days in the specified month and year.
Returns a value indicating whether this instance is equal to the
  Equals(DateTime)
specified DateTime instance.
Returns a value indicating whether this instance is equal to a
  Equals(Object)
specified object. (Overrides ValueType.Equals(Object).)
Equals(DateTime, Returns a value indicating whether two instances
   
DateTime) of DateTime are equal.
Allows an object to try to free resources and perform other
  Finalize cleanup operations before it is reclaimed by garbage
collection. (Inherited from Object.)
Deserializes a 64-bit binary value and recreates an original
  FromBinary
serialized DateTime object.
Converts the specified Windows file time to an equivalent local
    FromFileTime
time.
Converts the specified Windows file time to an equivalent
    FromFileTimeUtc
UTC time.
Returns a DateTime equivalent to the specified OLE
    FromOADate
Automation Date.
Converts the value of this instance to all the string
  GetDateTimeFormats() representations supported by the standard date and time format
specifiers.
Converts the value of this instance to all the string
GetDateTimeFormats(Ch
  representations supported by the specified standard date and
ar)
time format specifier.
Converts the value of this instance to all the string
GetDateTimeFormats(IF representations supported by the standard date and time format
 
ormatProvider) specifiers and the specified culture-specific formatting
information.
Converts the value of this instance to all the string
GetDateTimeFormats(Ch representations supported by the specified standard date and
 
ar, IFormatProvider) time format specifier and culture-specific formatting
information.
Returns the hash code for this
  GetHashCode
instance. (Overrides ValueType.GetHashCode().)
  GetType Gets the Type of the current instance. (Inherited from Object.)
  GetTypeCode Returns the TypeCode for value type DateTime.
Indicates whether this instance of DateTime is within the
  IsDaylightSavingTime
daylight saving time range for the current time zone.
    IsLeapYear Returns an indication whether the specified year is a leap year.
Creates a shallow copy of the current Object. (Inherited
  MemberwiseClone
from Object.)
Converts the specified string representation of a date and time
    Parse(String)
to its DateTime equivalent.
Converts the specified string representation of a date and time
Parse(String,
    to its DateTime equivalent using the specified culture-specific
IFormatProvider)
format information.
Parse(String, Converts the specified string representation of a date and time
    IFormatProvider, to its DateTime equivalent using the specified culture-specific
DateTimeStyles) format information and formatting style.
Converts the specified string representation of a date and time
ParseExact(String, to its DateTime equivalent using the specified format and
   
String, IFormatProvider) culture-specific format information. The format of the string
representation must match the specified format exactly.
Converts the specified string representation of a date and time
ParseExact(String, to its DateTime equivalent using the specified format, culture-
    String, IFormatProvider, specific format information, and style. The format of the string
DateTimeStyles) representation must match the specified format exactly or an
exception is thrown.
    ParseExact(String, String Converts the specified string representation of a date and time
[], IFormatProvider, to its DateTime equivalent using the specified array of formats,
DateTimeStyles) culture-specific format information, and style. The format of
the string representation must match at least one of the
specified formats exactly or an exception is thrown.
Creates a new DateTime object that has the same number of
ticks as the specified DateTime, but is designated as either
    SpecifyKind
local time, Coordinated Universal Time (UTC), or neither, as
indicated by the specified DateTimeKind value.
  Subtract(DateTime) Subtracts the specified date and time from this instance.
  Subtract(TimeSpan) Subtracts the specified duration from this instance.
Serializes the current DateTime object to a 64-bit binary value
ToBinary
that subsequently can be used to recreate the DateTimeobject.
Converts the value of the current DateTime object to a
  ToFileTime
Windows file time.
Converts the value of the current DateTime object to a
  ToFileTimeUtc
Windows file time.
Converts the value of the current DateTime object to local
  ToLocalTime
time.
Converts the value of the current DateTime object to its
  ToLongDateString
equivalent long date string representation.
Converts the value of the current DateTime object to its
  ToLongTimeString
equivalent long time string representation.
Converts the value of this instance to the equivalent OLE
  ToOADate
Automation date.
Converts the value of the current DateTime object to its
  ToShortDateString
equivalent short date string representation.
Converts the value of the current DateTime object to its
  ToShortTimeString
equivalent short time string representation.
Converts the value of the current DateTime object to its
  ToString() equivalent string
representation. (OverridesValueType.ToString().)
Converts the value of the current DateTime object to its
ToString(IFormatProvide
  equivalent string representation using the specified culture-
r)
specific format information.
Converts the value of the current DateTime object to its
  ToString(String)
equivalent string representation using the specified format.
Converts the value of the current DateTime object to its
ToString(String,
  equivalent string representation using the specified format and
IFormatProvider)
culture-specific format information.
Converts the value of the current DateTime object to
  ToUniversalTime
Coordinated Universal Time (UTC).
Converts the specified string representation of a date and time
TryParse(String,
  to its DateTime equivalent and returns a value that indicates
DateTime)
whether the conversion succeeded.
TryParse(String, Converts the specified string representation of a date and time
IFormatProvider, to its DateTime equivalent using the specified culture-specific
 
DateTimeStyles, format information and formatting style, and returns a value
DateTime) that indicates whether the conversion succeeded.
Converts the specified string representation of a date and time
TryParseExact(String, to its DateTime equivalent using the specified format, culture-
String, IFormatProvider, specific format information, and style. The format of the string
 
DateTimeStyles, representation must match the specified format exactly. The
DateTime) method returns a value that indicates whether the conversion
succeeded.
Converts the specified string representation of a date and time
TryParseExact(String, St to its DateTime equivalent using the specified array of formats,
ring[], IFormatProvider, culture-specific format information, and style. The format of
 
DateTimeStyles, the string representation must match at least one of the
DateTime) specified formats exactly. The method returns a value that
indicates whether the conversion succeeded.
Top

Operators

  Name Description
Adds a specified time interval to a specified date and time,
    Addition
yielding a new date and time.
Determines whether two specified instances of DateTime are
    Equality
equal.
Determines whether one specified DateTime is greater than
    GreaterThan
another specified DateTime.
Determines whether one specified DateTime is greater than
    GreaterThanOrEqual
or equal to another specified DateTime.
Determines whether two specified instances of DateTime are
    Inequality
not equal.
Determines whether one specified DateTime is less than
    LessThan
another specified DateTime.
Determines whether one specified DateTime is less than or
    LessThanOrEqual
equal to another specified DateTime.
Subtraction(DateTime, Subtracts a specified date and time from another specified
   
DateTime) date and time and returns a time interval.
Subtraction(DateTime, Subtracts a specified time interval from a specified date and
   
TimeSpan) time and returns a new date and time.
Top

Fields

  Name Description
    MaxValue Represents the largest possible value of DateTime. This field is read-only.
    MinValue Represents the smallest possible value of DateTime. This field is read-only.
Top

Explicit Interface Implementations

  Name Description
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToBoolean
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToByte
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToChar
to use this method throws an InvalidCastException.
    IConvertible.ToDateTime Infrastructure. Returns the current DateTime object.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToDecimal
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToDouble
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToInt16
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToInt32
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToInt64
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToSByte
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToSingle
to use this method throws an InvalidCastException.
Infrastructure. Converts the current DateTime object to an
    IConvertible.ToType
object of a specified type.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToUInt16
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToUInt32
to use this method throws an InvalidCastException.
Infrastructure. This conversion is not supported. Attempting
    IConvertible.ToUInt64
to use this method throws an InvalidCastException.
Populates a SerializationInfo object with the data needed to
  ISerializable.GetObjectData
serialize the current DateTime object.
Top

Remarks
The DateTime value type represents dates and times with values ranging from 12:00:00 midnight,
January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D.
(C.E.).
Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks
since 12:00 midnight, January 1, 0001 A.D. (C.E.) in theGregorianCalendar calendar (excluding ticks that would
be added by leap seconds). For example, a ticks value of 31241376000000000L represents the date, Friday,
January 01, 0100 12:00:00 midnight. A DateTime value is always expressed in the context of an explicit or default
calendar.

 Note
   If you are working with a ticks value that you want to convert to some other time interval, such
as minutes or seconds, you should use
the TimeSpan.TicksPerDay,TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.Ticks
PerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to
add the number of seconds represented by a specified number of ticks to the Second component of
a DateTime value, you can use the expression dateValue.Second +
nTicks/Timespan.TicksPerSecond.

Instantiating a DateTime Object


You can create a new DateTime value in any of the following ways:
• By calling any of the overloads of the DateTime constructor that allow you to specify specific elements of
the date and time value (such as the year, month, and day, or the number of ticks). The following
statement illustrates a call to one of the DateTime constructors to create a date with a specific year,
month, day, hour, minute, and second.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);

• By using any compiler-specific syntax for declaring date and time values. For example, the following
Visual Basic statement initializes a new DateTime value.
VB
C#
C++
F#
JScript
Copy

This language is not supported or no code example is available.


• By assigning the DateTime object a date and time value returned by a property or method. The following
example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time,
and the current date to three new DateTime variables.
VB
C#
C++
F#
JScript
Copy
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;

• By parsing the string representation of a date and time value. The Parse, ParseExact, TryParse,


and TryParseExact methods all convert a string to its equivalent date and time value. The following
example uses the Parse method to parse a string and convert it to a DateTime value.
VB
C#
C++
F#
JScript
Copy

string dateString = "5/1/2008 8:30:52 AM";


DateTime date1 = DateTime.Parse(dateString,
System.Globalization.CultureInfo.InvariantCulture);

Note that the TryParse and TryParseExact methods indicate whether a particular string contains a valid


representation of a DateTime value in addition to performing the conversion.
• By calling the DateTime structure's implicit default constructor. (For details on the implicit default
constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers
that support it, is declaring a DateTime value without explicitly assigning a date and time to it. The
following example illustrates a call to the DateTime implicit default constructor in C# and Visual Basic, as
well as a DateTime variable declaration with no assignment in Visual Basic.
VB
C#
C++
F#
JScript
Copy

DateTime dat1 = new DateTime();


// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));

DateTime Values and Their String Representations


Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals)
that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the
way in which that value appears when displayed in a user interface element or when written to a file. The
appearance of a DateTimevalue is the result of a formatting operation. Formatting is the process of converting a
value to its string representation.
Because the appearance of date and time values is dependent on such factors as culture, international
standards, application requirements, and personal preference, theDateTime structure offers a great deal of
flexibility in formatting date and time values through the overloads of its ToString method. The
default DateTime.ToString() method returns the string representation of a date and time value using the current
culture's short date and long time pattern. The following example uses the defaultDateTime.ToString() method
to display the date and time using the short date and long time pattern for the en-US culture, the current
culture on the computer on which the example was run.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);


Console.WriteLine(date1.ToString());
// For en-US culture, displays 3/1/2008 7:00:00 AM

The DateTime.ToString(IFormatProvider) method returns the string representation of a date and time value


using the short date and long time pattern of a specific culture. The following example uses
the DateTime.ToString(IFormatProvider) method to display the date and time using the short date and long
time pattern for the fr-FR culture.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);


Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("
fr-FR")));
// Displays 01/03/2008 07:00:00

The DateTime.ToString(String) method returns the string representation of the date and time in a format
defined by a standard or custom format specifier and using the formatting conventions of the current culture.
The following example uses the DateTime.ToString(String) method to display the full date and time pattern for
the en-US culture, the current culture on the computer on which the example was run.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);


Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM

The DateTime.ToString(String, IFormatProvider) method returns the string representation of the date and time
in a format defined by a specific format specifier and using the formatting conventions of a specific culture. The
following example uses the DateTime.ToString(String, IFormatProvider) method to display the full date and time
pattern for the fr-FR culture.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);


Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR")));
// Displays samedi 1 mars 2008 07:00:00

Version Considerations
Prior to the .NET Framework version 2.0, the DateTime structure contains a 64-bit field composed of an unused
2-bit field concatenated with a private Ticks field, which is a 62-bit unsigned field that contains the number of
ticks that represent the date and time. The value of the Ticks field can be obtained with the Ticks property.
Starting with the .NET Framework 2.0, the DateTime structure contains a 64-bit field composed of a private Kind
field concatenated with the Ticks field. The Kind field is a 2-bit field that indicates whether
the DateTime structure represents a local time, a Coordinated Universal Time (UTC), or the time in an
unspecified time zone. The Kind field is used when performing time conversions between time zones, but not
for time comparisons or arithmetic. The value of the Kind field can be obtained with the Kind property.

 Note
An alternative to the DateTime structure for working with date and time values in particular time
zones is the DateTimeOffset structure. The DateTimeOffset structure stores date and time
information in a private DateTime field and the number of minutes by which that date and time
differs from UTC in a private Int16 field. This makes it possible for a DateTimeOffset value to
reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect
only UTC and the local time zone's time. For a discussion about when to use
the DateTime structure or the DateTimeOffset structure when working with date and time values,
see Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo.

DateTime Values
Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time
(UTC) standard, which is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated
Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is
not applicable to UTC.
Local time is relative to a particular time zone. A time zone is associated with a time zone offset, which is the
displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally
affected by daylight saving time, which adds or subtracts an hour from the length of a day. Consequently, local
time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The
time zone offset at the UTC origin point is zero.
UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate
for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web
applications) also need to work with a number of other time zones.
If the Kind property of a DateTime object is DateTimeKind.Unspecified, it is unspecified whether the time
represented is local time, UTC time, or a time in some other time zone.

DateTime Operations
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure.
Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.
Conversion operations between time zones (such as between UTC and local time, or between one time zone
and another) take daylight saving time into account, but arithmetic and comparison operations do not.
The DateTime structure itself offers limited support for converting from one time zone to another. You can use
the ToLocalTime method to convert UTC to local time, or you can use the ToUniversalTime method to convert
from local time to UTC. However, a full set of time zone conversion methods is available in
the TimeZoneInfo class. Using these methods, you can convert the time in any one of the world's time zones to
the time in any other time zone.
Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the
same time zone. You can use a TimeZoneInfo object to represent aDateTime value's time zone, although the
two are loosely coupled. (That is, a DateTime object does not have a property that returns an object that
represents that date and time value's time zone other than the Kind property.) For this reason, in a time zone-
aware application, you must rely on some external mechanism to determine the time zone in which
a DateTime object was created. For example, you could use a structure that wraps both the DateTime value and
the TimeZoneInfo object that represents the DateTimevalue's time zone. For details on using UTC in calculations
and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.
Each DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of
constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such
as System.Globalization.DateTimeFormatInfo, that implicitly specifies a calendar.
Operations by members of the DateTime type take into account details such as leap years and the number of
days in a month.

DateTime vs. TimeSpan


The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas
a TimeSpan represents a time interval. This means, for example, that you can subtract one instance
of DateTime from another to obtain a TimeSpan object that represents the time interval between them. Or you
could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future
date.
You can add or subtract a time interval from a DateTime object. Time intervals can be negative or positive, can
be expressed in units such as ticks or seconds, or can be expressed as a TimeSpan object.

COM Interop Considerations


A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is
said to round-trip. However, a DateTime value that specifies only a time does not round-trip as you might
expect.
If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M.,
instead of January, 1, 0001 C.E. at 3:00 P.M. This happens because the .NET Framework and COM assume a
default date when only a time is specified. However, the COM system assumes a base date of December 30,
1899 C.E. while the .NET Framework assumes a base date of January, 1, 0001 C.E.
When only a time is passed from the .NET Framework to COM, special processing is performed that converts the
time to the format used by COM. When only a time is passed from COM to the .NET Framework, no special
processing is performed because that would corrupt legitimate dates and times on or before December 30,
1899. This also means if a date starts its round-trip from COM, the .NET Framework and COM preserve the date.
The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only
specifies a time, your application must remember to modify or ignore the erroneous date from the
final DateTime object.

Examples

The following example demonstrates how to compare roughly equivalent DateTime values,


accepting a small margin of difference when declaring them equal.
VB
C#
C++
F#
JScript
Copy

using System;

class DateTimeTester
{
static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds,
int frequencyInSeconds)
{
long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds
% frequencyInSeconds;

delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;

return Math.Abs(delta) < windowInSeconds;


}

public static void Main()


{
int window = 10;
int freq = 60 * 60 * 2; // 2 hours;

DateTime d1 = DateTime.Now;

DateTime d2 = d1.AddSeconds(2 * window);


DateTime d3 = d1.AddSeconds(-2 * window);
DateTime d4 = d1.AddSeconds(window / 2);
DateTime d5 = d1.AddSeconds(-window / 2);

DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);


DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
DateTime d9 = (d1.AddHours(2)).AddSeconds(-window / 2);

Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}",


d1, d1, RoughlyEquals(d1, d1, window, freq));
Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}",
d1, d2, RoughlyEquals(d1, d2, window, freq));
Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}",
d1, d3, RoughlyEquals(d1, d3, window, freq));
Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}",
d1, d4, RoughlyEquals(d1, d4, window, freq));
Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}",
d1, d5, RoughlyEquals(d1, d5, window, freq));

Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}",


d1, d6, RoughlyEquals(d1, d6, window, freq));
Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}",
d1, d7, RoughlyEquals(d1, d7, window, freq));
Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}",
d1, d8, RoughlyEquals(d1, d8, window, freq));
Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}",
d1, d9, RoughlyEquals(d1, d9, window, freq));
}
}
// The example displays output similar to the following:
// d1 (1/28/2010 9:01:26 PM) ~= d1 (1/28/2010 9:01:26 PM): True
// d1 (1/28/2010 9:01:26 PM) ~= d2 (1/28/2010 9:01:46 PM): False
// d1 (1/28/2010 9:01:26 PM) ~= d3 (1/28/2010 9:01:06 PM): False
// d1 (1/28/2010 9:01:26 PM) ~= d4 (1/28/2010 9:01:31 PM): True
// d1 (1/28/2010 9:01:26 PM) ~= d5 (1/28/2010 9:01:21 PM): True
// d1 (1/28/2010 9:01:26 PM) ~= d6 (1/28/2010 11:01:46 PM): False
// d1 (1/28/2010 9:01:26 PM) ~= d7 (1/28/2010 11:01:06 PM): False
// d1 (1/28/2010 9:01:26 PM) ~= d8 (1/28/2010 11:01:31 PM): True
// d1 (1/28/2010 9:01:26 PM) ~= d9 (1/28/2010 11:01:21 PM): True

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Custom Date and Time Format Strings

.NET Framework 4

Other Versions

Updated: July 2010


A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results
from a formatting operation . It can also define the representation of a date and time value that is required in a
parsing operation in order to successfully convert the string to a date and time. A custom format string consists
of one or more custom date and time format specifiers. Any string that is not a standard date and time format
string is interpreted as a custom date and time format string.

Note
Custom date and time format strings can be used with
both DateTime and DateTimeOffset values.
In formatting operations, custom date and time format strings can be used either with
the ToString method of a date and time instance or with a method that supports composite
formatting. The following example illustrates both uses.
VB
C#
C++
F#
JScript
Copy

DateTime thisDate1 = new DateTime(2011, 6, 10);


Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16,


TimeSpan.Zero);
Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}",
thisDate2);
// The example displays the following output:
// Today is June 10, 2011.
// The current date and time: 06/10/11 15:24:16 +00:00

In parsing operations, custom date and time format strings can be used with
the DateTime.ParseExact, DateTime.TryParseExact, DateTimeOffset.ParseExact,
andDateTimeOffset.TryParseExact methods. These methods require that an input string conform exactly to a
particular pattern for the parse operation to succeed. The following example illustrates a call to
the DateTimeOffset.ParseExact(String, String, IFormatProvider) method to parse a date that must include a day,
a month, and a two-digit year.
VB
C#
C++
F#
JScript
Copy

using System;
using System.Globalization;

public class Example


{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;

foreach (var dateValue in dateValues) {


if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.

The following table describes the custom date and time format specifiers and displays a result string produced
by each format specifier. If a particular format specifier produces a localized result string, the example also notes
the culture to which the result string applies. See the Notes section for additional information about using
custom date and time format strings.

Format
Description Examples
specifier

"d" The day of the month, from 1 6/1/2009 1:45:30 PM -> 1


through 31.
More information: The "d" Custom 6/15/2009 1:45:30 PM -> 15
Format Specifier.
The day of the month, from 01
through 31. 6/1/2009 1:45:30 PM -> 01
"dd"
More information: The "dd" Custom 6/15/2009 1:45:30 PM -> 15
Format Specifier.
The abbreviated name of the day of
6/15/2009 1:45:30 PM -> Mon (en-US)
the week.
"ddd" 6/15/2009 1:45:30 PM -> Пн (ru-RU)
More information: The "ddd"
6/15/2009 1:45:30 PM -> lun. (fr-FR)
Custom Format Specifier.
The full name of the day of the 6/15/2009 1:45:30 PM -> Monday (en-US)
week. 6/15/2009 1:45:30 PM -> понедельник (ru-
"dddd"
More information: The "dddd" RU)
Custom Format Specifier. 6/15/2009 1:45:30 PM -> lundi (fr-FR)
The tenths of a second in a date and
time value. 6/15/2009 13:45:30.617 -> 6
"f"
More information: The "f" Custom 6/15/2009 13:45:30.050 -> 0
Format Specifier.
The hundredths of a second in a date
and time value. 6/15/2009 13:45:30.617 -> 61
"ff"
More information: The "ff" Custom 6/15/2009 13:45:30.005 -> 00
Format Specifier.
The milliseconds in a date and time
value. 6/15/2009 13:45:30.617 -> 617
"fff"
More information: The "fff" Custom 6/15/2009 13:45:30.0005 -> 000
Format Specifier.
The ten thousandths of a second in a
date and time value. 6/15/2009 13:45:30.6175 -> 6175
"ffff"
More information: The "ffff" 6/15/2009 13:45:30.00005 -> 0000
Custom Format Specifier.
The hundred thousandths of a
second in a date and time value. 6/15/2009 13:45:30.61754 -> 61754
"fffff"
More information: The "fffff" 6/15/2009 13:45:30.000005 -> 00000
Custom Format Specifier.
The millionths of a second in a date
and time value. 6/15/2009 13:45:30.617542 -> 617542
"ffffff"
More information: The "ffffff" 6/15/2009 13:45:30.0000005 -> 000000
Custom Format Specifier.
The ten millionths of a second in a
date and time value. 6/15/2009 13:45:30.6175425 -> 6175425
"fffffff"
More information: The "fffffff" 6/15/2009 13:45:30.0001150 -> 0001150
Custom Format Specifier.
If non-zero, the tenths of a second in
a date and time value. 6/15/2009 13:45:30.617 -> 6
"F"
More information: The "F" Custom 6/15/2009 13:45:30.050 -> (no output)
Format Specifier.
If non-zero, the hundredths of a
second in a date and time value. 6/15/2009 13:45:30.617 -> 61
"FF"
More information: The "FF" 6/15/2009 13:45:30.005 -> (no output)
Custom Format Specifier.
If non-zero, the milliseconds in a 6/15/2009 13:45:30.617 -> 617
date and time value. 6/15/2009 13:45:30.0005 -> (no output)
"FFF"
More information: The "FFF"
Custom Format Specifier.
If non-zero, the ten thousandths of a 6/1/2009 13:45:30.5275 -> 5275
second in a date and time value. 6/15/2009 13:45:30.00005 -> (no output)
"FFFF"
More information: The "FFFF"
Custom Format Specifier.
If non-zero, the hundred
thousandths of a second in a date
6/15/2009 13:45:30.61754 -> 61754
"FFFFF" and time value.
6/15/2009 13:45:30.000005 -> (no output)
More information: The "FFFFF"
Custom Format Specifier.
If non-zero, the millionths of a 6/15/2009 13:45:30.617542 -> 617542
second in a date and time value. 6/15/2009 13:45:30.0000005 -> (no output)
"FFFFFF"
More information: The "FFFFFF"
Custom Format Specifier.
If non-zero, the ten millionths of a 6/15/2009 13:45:30.6175425 -> 6175425
second in a date and time value. 6/15/2009 13:45:30.0001150 -> 000115
"FFFFFFF"
More information: The "FFFFFFF"
Custom Format Specifier.
The period or era.
"g", "gg" More information: The "g" or "gg" 6/15/2009 1:45:30 PM -> A.D.
Custom Format Specifier.
The hour, using a 12-hour clock 6/15/2009 1:45:30 AM -> 1
from 1 to 12. 6/15/2009 1:45:30 PM -> 1
"h"
More information: The "h" Custom
Format Specifier.
The hour, using a 12-hour clock 6/15/2009 1:45:30 AM -> 01
from 01 to 12. 6/15/2009 1:45:30 PM -> 01
"hh"
More information: The "hh" Custom
Format Specifier.
The hour, using a 24-hour clock 6/15/2009 1:45:30 AM -> 1
from 0 to 23. 6/15/2009 1:45:30 PM -> 13
"H"
More information: The "H" Custom
Format Specifier.
The hour, using a 24-hour clock 6/15/2009 1:45:30 AM -> 01
from 00 to 23. 6/15/2009 1:45:30 PM -> 13
"HH"
More information: The "HH"
Custom Format Specifier.
"K" Time zone information. With DateTime values:
More information: The "K" Custom 6/15/2009 1:45:30 PM, Kind Unspecified ->
Format Specifier. 6/15/2009 1:45:30 PM, Kind Utc -> Z
6/15/2009 1:45:30 PM, Kind Local -> -07:00
(depends on local computer settings)
With DateTimeOffset values:
6/15/2009 1:45:30 AM -07:00 --> -07:00
6/15/2009 8:45:30 AM +00:00 --> +00:00
The minute, from 0 through 59.
6/15/2009 1:09:30 AM -> 9
"m" More information: The "m" Custom
6/15/2009 1:09:30 PM -> 9
Format Specifier.
The minute, from 00 through 59.
6/15/2009 1:09:30 AM -> 09
"mm" More information: The "mm"
6/15/2009 1:09:30 PM -> 09
Custom Format Specifier.
The month, from 1 through 12.
"M" More information: The "M" Custom 6/15/2009 1:45:30 PM -> 6
Format Specifier.
The month, from 01 through 12.
"MM" More information: The "MM" 6/15/2009 1:45:30 PM -> 06
Custom Format Specifier.
The abbreviated name of the month. 6/15/2009 1:45:30 PM -> Jun (en-US)
"MMM" More information: The "MMM" 6/15/2009 1:45:30 PM -> juin (fr-FR)
Custom Format Specifier. 6/15/2009 1:45:30 PM -> Jun (zu-ZA)
The full name of the month. 6/15/2009 1:45:30 PM -> June (en-US)
"MMMM" More information: The "MMMM" 6/15/2009 1:45:30 PM -> juni (da-DK)
Custom Format Specifier. 6/15/2009 1:45:30 PM -> uJuni (zu-ZA)
The second, from 0 through 59.
"s" More information: The "s" Custom 6/15/2009 1:45:09 PM -> 9
Format Specifier.
The second, from 00 through 59.
"ss" More information: The "ss" Custom 6/15/2009 1:45:09 PM -> 09
Format Specifier.
The first character of the AM/PM 6/15/2009 1:45:30 PM -> P (en-US)
designator.
"t" 6/15/2009 1:45:30 PM -> 午 (ja-JP)
More information: The "t" Custom
Format Specifier. 6/15/2009 1:45:30 PM -> (fr-FR)

The AM/PM designator. 6/15/2009 1:45:30 PM -> PM (en-US)


"tt" More information: The "tt" Custom 6/15/2009 1:45:30 PM -> 午後 (ja-JP)
Format Specifier. 6/15/2009 1:45:30 PM -> (fr-FR)
1/1/0001 12:00:00 AM -> 1
The year, from 0 to 99.
1/1/0900 12:00:00 AM -> 0
"y" More information: The "y" Custom
1/1/1900 12:00:00 AM -> 0
Format Specifier.
6/15/2009 1:45:30 PM -> 9
1/1/0001 12:00:00 AM -> 01
The year, from 00 to 99.
1/1/0900 12:00:00 AM -> 00
"yy" More information: The "yy" Custom
1/1/1900 12:00:00 AM -> 00
Format Specifier.
6/15/2009 1:45:30 PM -> 09
"yyy" The year, with a minimum of three 1/1/0001 12:00:00 AM -> 001
digits. 1/1/0900 12:00:00 AM -> 900
More information: The "yyy" 1/1/1900 12:00:00 AM -> 1900
Custom Format Specifier. 6/15/2009 1:45:30 PM -> 2009
1/1/0001 12:00:00 AM -> 0001
The year as a four-digit number.
1/1/0900 12:00:00 AM -> 0900
"yyyy" More information: The "yyyy"
1/1/1900 12:00:00 AM -> 1900
Custom Format Specifier.
6/15/2009 1:45:30 PM -> 2009
The year as a five-digit number.
1/1/0001 12:00:00 AM -> 00001
"yyyyy" More information: The "yyyyy"
6/15/2009 1:45:30 PM -> 02009
Custom Format Specifier.
Hours offset from UTC, with no
leading zeros.
"z" 6/15/2009 1:45:30 PM -07:00 -> -7
More information: The "z" Custom
Format Specifier.
Hours offset from UTC, with a
leading zero for a single-digit value.
"zz" 6/15/2009 1:45:30 PM -07:00 -> -07
More information: The "zz" Custom
Format Specifier.
Hours and minutes offset from
UTC.
"zzz" 6/15/2009 1:45:30 PM -07:00 -> -07:00
More information: The "zzz"
Custom Format Specifier.
The time separator. 6/15/2009 1:45:30 PM -> : (en-US)
":" More information: The ":" Custom 6/15/2009 1:45:30 PM -> . (it-IT)
Format Specifier. 6/15/2009 1:45:30 PM -> : (ja-JP)
The date separator. 6/15/2009 1:45:30 PM -> / (en-US)
"/" More Information: The "/" Custom 6/15/2009 1:45:30 PM -> - (ar-DZ)
Format Specifier. 6/15/2009 1:45:30 PM -> . (tr-TR)
6/15/2009 1:45:30 PM ("arr:" h:m t) -> arr:
"string" 1:45 P
Literal string delimiter.
'string' 6/15/2009 1:45:30 PM ('arr:' h:m t) -> arr:
1:45 P
Defines the following character as a
custom format specifier.
% 6/15/2009 1:45:30 PM (%h) -> 1
More information: Using Single
Custom Format Specifiers.
\ The escape character. 6/15/2009 1:45:30 PM (h \h) -> 1 h
The character is copied to the result
Any other string unchanged. 6/15/2009 1:45:30 AM (arr hh:mm t) -> arr
character More information: Using the Escape 01:45 A
Character.
The following sections provide additional information about each custom date and time format specifier. Unless
otherwise noted, each specifier produces an identical string representation regardless of whether it is used with
a DateTime value or a DateTimeOffset value.

The "d" Custom Format Specifier


The "d" custom format specifier represents the day of the month as a number from 1 through 31. A
single-digit day is formatted without a leading zero.
If the "d" format specifier is used without other custom format specifiers, it is interpreted as the "d" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "d" custom format specifier in several format strings.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15);

Console.WriteLine(date1.ToString("d, M",
CultureInfo.InvariantCulture));
// Displays 29, 8

Console.WriteLine(date1.ToString("d MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays 29 August
Console.WriteLine(date1.ToString("d MMMM",
CultureInfo.CreateSpecificCulture("es-MX")));
// Displays 29 agosto

Back to table

The "dd" Custom Format Specifier

The "dd" custom format string represents the day of the month as a number from 01 through 31. A
single-digit day is formatted with a leading zero.
The following example includes the "dd" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 1, 2, 6, 30, 15);

Console.WriteLine(date1.ToString("dd, MM",
CultureInfo.InvariantCulture));
// 02, 01

Back to table
The "ddd" Custom Format Specifier

The "ddd" custom format specifier represents the abbreviated name of the day of the week. The
localized abbreviated name of the day of the week is retrieved from
theDateTimeFormatInfo.AbbreviatedDayNames property of the current or specified culture.
The following example includes the "ddd" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15);

Console.WriteLine(date1.ToString("ddd d MMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Fri 29 Aug
Console.WriteLine(date1.ToString("ddd d MMM",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays ven. 29 août

Back to table

The "dddd" Custom Format Specifier

The "dddd" custom format specifier (plus any number of additional "d" specifiers) represents the
full name of the day of the week. The localized name of the day of the week is retrieved from
the DateTimeFormatInfo.DayNames property of the current or specified culture.
The following example includes the "dddd" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15);

Console.WriteLine(date1.ToString("dddd dd MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Friday 29 August
Console.WriteLine(date1.ToString("dddd dd MMMM",
CultureInfo.CreateSpecificCulture("it-IT")));
// Displays venerdì 29 agosto

Back to table
The "f" Custom Format Specifier

The "f" custom format specifier represents the most significant digit of the seconds fraction; that is,
it represents the tenths of a second in a date and time value.
If the "f" format specifier is used without other format specifiers, it is interpreted as the "f" standard date and
time format specifier. For more information about using a single format specifier, see Using Single Custom
Format Specifiers later in this topic.
When you use "f" format specifiers as part of a format string supplied to
the ParseExact, TryParseExact, ParseExact, or TryParseExact method, the number of "f" format specifiers indicates
the number of most significant digits of the seconds fraction that must be present to successfully parse the
string.
The following example includes the "f" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;

Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "ff" Custom Format Specifier

The "ff" custom format specifier represents the two most significant digits of the seconds fraction;
that is, it represents the hundredths of a second in a date and time value.
following example includes the "ff" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;

Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "fff" Custom Format Specifier

The "fff" custom format specifier represents the three most significant digits of the seconds fraction;
that is, it represents the milliseconds in a date and time value.
The following example includes the "fff" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;

Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "ffff" Custom Format Specifier


The "ffff" custom format specifier represents the four most significant digits of the seconds fraction;
that is, it represents the ten thousandths of a second in a date and time value.
Although it is possible to display the ten thousandths of a second component of a time value, that value may
not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the
Windows NT version 3.5 (and later) and Windows Vista operating systems, the clock's resolution is
approximately 10-15 milliseconds.
Back to table

The "fffff" Custom Format Specifier

The "fffff" custom format specifier represents the five most significant digits of the seconds
fraction; that is, it represents the hundred thousandths of a second in a date and time value.
Although it is possible to display the hundred thousandths of a second component of a time value, that value
may not be meaningful. The precision of date and time values depends on the resolution of the system clock.
On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is
approximately 10-15 milliseconds.
Back to table

The "ffffff" Custom Format Specifier

The "ffffff" custom format specifier represents the six most significant digits of the seconds
fraction; that is, it represents the millionths of a second in a date and time value.
Although it is possible to display the millionths of a second component of a time value, that value may not be
meaningful. The precision of date and time values depends on the resolution of the system clock. On the
Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15
milliseconds.
Back to table

The "fffffff" Custom Format Specifier

The "fffffff" custom format specifier represents the seven most significant digits of the seconds
fraction; that is, it represents the ten millionths of a second in a date and time value.
Although it is possible to display the ten millionths of a second component of a time value, that value may not
be meaningful. The precision of date and time values depends on the resolution of the system clock. On the
Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15
milliseconds.
Back to table

The "F" Custom Format Specifier


The "F" custom format specifier represents the most significant digit of the seconds fraction; that is,
it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
If the "F" format specifier is used without other format specifiers, it is interpreted as the "F" standard date and
time format specifier. For more information about using a single format specifier, see Using Single Custom
Format Specifiers later in this topic.
The number of "F" format specifiers used with the ParseExact, TryParseExact, ParseExact,
or TryParseExact method indicates the maximum number of most significant digits of the seconds fraction that
can be present to successfully parse the string.
The following example includes the "F" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;

Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "FF" Custom Format Specifier

The "FF" custom format specifier represents the two most significant digits of the seconds fraction;
that is, it represents the hundredths of a second in a date and time value. However, trailing zeros or
two zero digits are not displayed.
The following example includes the "FF" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;
Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "FFF" Custom Format Specifier

The "FFF" custom format specifier represents the three most significant digits of the seconds
fraction; that is, it represents the milliseconds in a date and time value. However, trailing zeros or
three zero digits are not displayed.
The following example includes the "FFF" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18);


CultureInfo ci = CultureInfo.InvariantCulture;

Console.WriteLine(date1.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0
Console.WriteLine(date1.ToString("hh:mm:ss.F", ci));
// Displays 07:27:15
Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci));
// Displays 07:27:15.01
Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci));
// Displays 07:27:15.018
Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci));
// Displays 07:27:15.018

Back to table

The "FFFF" Custom Format Specifier


The "FFFF" custom format specifier represents the four most significant digits of the seconds
fraction; that is, it represents the ten thousandths of a second in a date and time value. However,
trailing zeros or four zero digits are not displayed.
Although it is possible to display the ten thousandths of a second component of a time value, that value may
not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the
Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15
milliseconds.
Back to table

The "FFFFF" Custom Format Specifier

The "FFFFF" custom format specifier represents the five most significant digits of the seconds
fraction; that is, it represents the hundred thousandths of a second in a date and time value.
However, trailing zeros or five zero digits are not displayed.
Although it is possible to display the hundred thousandths of a second component of a time value, that value
may not be meaningful. The precision of date and time values depends on the resolution of the system clock.
On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is
approximately 10-15 milliseconds.
Back to table

The "FFFFFF" Custom Format Specifier

The "FFFFFF" custom format specifier represents the six most significant digits of the seconds
fraction; that is, it represents the millionths of a second in a date and time value. However, trailing
zeros or six zero digits are not displayed.
Although it is possible to display the millionths of a second component of a time value, that value may not be
meaningful. The precision of date and time values depends on the resolution of the system clock. On tfhe
Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15
milliseconds.
Back to table

The "FFFFFFF" Custom Format Specifier

The "FFFFFFF" custom format specifier represents the seven most significant digits of the seconds
fraction; that is, it represents the ten millionths of a second in a date and time value. However,
trailing zeros or seven zero digits are not displayed.
Although it is possible to display the ten millionths of a second component of a time value, that value may not
be meaningful. The precision of date and time values depends on the resolution of the system clock. On the
Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15
milliseconds.
Back to table
The "g" or "gg" Custom Format Specifier

The "g" or "gg" custom format specifiers (plus any number of additional "g" specifiers) represents
the period or era, such as A.D. The formatting operation ignores this specifier if the date to be
formatted does not have an associated period or era string.
If the "g" format specifier is used without other custom format specifiers, it is interpreted as the "g" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "g" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(70, 08, 04);

Console.WriteLine(date1.ToString("MM/dd/yyyy g",
CultureInfo.InvariantCulture));
// Displays 08/04/0070 A.D.
Console.WriteLine(date1.ToString("MM/dd/yyyy g",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 08/04/0070 ap. J.-C.

Back to table

The "h" Custom Format Specifier

The "h" custom format specifier represents the hour as a number from 1 through 12; that is, the hour
is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular
hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded,
and a single-digit hour is formatted without a leading zero. For example, given a time of 5:43 in the
morning or afternoon, this custom format specifier displays "5".
If the "h" format specifier is used without other custom format specifiers, it is interpreted as a standard date and
time format specifier and throws a FormatException. For more information about using a single format specifier,
see Using Single Custom Format Specifiers later in this topic.
The following example includes the "h" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1 µ
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1.5 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1.5 µ

Back to table

The "hh" Custom Format Specifier

The "hh" custom format specifier (plus any number of additional "h" specifiers) represents the hour
as a number from 01 through 12; that is, the hour is represented by a 12-hour clock that counts the
whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the
same hour after noon. The hour is not rounded, and a single-digit hour is formatted with a leading
zero. For example, given a time of 5:43 in the morning or afternoon, this format specifier displays
"05".
The following example includes the "hh" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01 PM
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01 du.
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01.50 PM
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01.50 du.

Back to table

The "H" Custom Format Specifier


The "H" custom format specifier represents the hour as a number from 0 through 23; that is, the
hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-
digit hour is formatted without a leading zero.
If the "H" format specifier is used without other custom format specifiers, it is interpreted as a standard date and
time format specifier and throws a FormatException. For more information about using a single format specifier,
see Using Single Custom Format Specifiers later in this topic.
The following example includes the "H" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1);


Console.WriteLine(date1.ToString("H:mm:ss",
CultureInfo.InvariantCulture));
// Displays 6:09:01

Back to table

The "HH" Custom Format Specifier

The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the
hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock
that counts the hours since midnight. A single-digit hour is formatted with a leading zero.
The following example includes the "HH" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1);


Console.WriteLine(date1.ToString("HH:mm:ss",
CultureInfo.InvariantCulture));
// Displays 06:09:01

Back to table

The "K" Custom Format Specifier


The "K" custom format specifier represents the time zone information of a date and time value.
When this format specifier is used with DateTime values, the result string is defined by the value of
the DateTime.Kind property:
• For the local time zone (a DateTime.Kind property value of DateTimeKind.Local), this specifier is
equivalent to the "zzz" specifier and produces a result string containing the local offset from Coordinated
Universal Time (UTC); for example, "-07:00".
• For a UTC time (a DateTime.Kind property value of DateTimeKind.Utc), the result string includes a "Z"
character to represent a UTC date.
• For a time from an unspecified time zone (a time whose DateTime.Kind property
equals DateTimeKind.Unspecified), the result is equivalent to String.Empty.
For DateTimeOffset values, the "K" format specifier is equivalent to the "zz" format specifier, and produces a
result string containing the DateTimeOffset value's offset from UTC.
If the "K" format specifier is used without other custom format specifiers, it is interpreted as a standard date and
time format specifier and throws a FormatException. For more information about using a single format specifier,
see Using Single Custom Format Specifiers later in this topic.
The following example displays the string that results from using the "K" custom format specifier with
various DateTime and DateTimeOffset values on a system in the U.S. Pacific Time zone.
VB
C#
C++
F#
JScript
Copy

Console.WriteLine(DateTime.Now.ToString("%K"));
// Displays -07:00
Console.WriteLine(DateTime.UtcNow.ToString("%K"));
// Displays Z
Console.WriteLine("'{0}'",
DateTime.SpecifyKind(DateTime.Now,
DateTimeKind.Unspecified).ToString("%K"));
// Displays ''
Console.WriteLine(DateTimeOffset.Now.ToString("%K"));
// Displays -07:00
Console.WriteLine(DateTimeOffset.UtcNow.ToString("%K"));
// Displays +00:00
Console.WriteLine(new DateTimeOffset(2008, 5, 1, 6, 30, 0,
new TimeSpan(5, 0, 0)).ToString("%K"));
// Displays +05:00

Back to table

The "m" Custom Format Specifier

The "m" custom format specifier represents the minute as a number from 0 through 59. The minute
represents whole minutes that have passed since the last hour. A single-digit minute is formatted
without a leading zero.
If the "m" format specifier is used without other custom format specifiers, it is interpreted as the "m" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "m" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1 µ
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1.5 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1.5 µ

Back to table

The "mm" Custom Format Specifier

The "mm" custom format specifier (plus any number of additional "m" specifiers) represents the
minute as a number from 00 through 59. The minute represents whole minutes that have passed
since the last hour. A single-digit minute is formatted with a leading zero.
The following example includes the "mm" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01 PM
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01 du.
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01.50 PM
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01.50 du.

Back to table

The "M" Custom Format Specifier

The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1
through 13 for calendars that have 13 months). A single-digit month is formatted without a leading
zero.
If the "M" format specifier is used without other custom format specifiers, it is interpreted as the "M" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "M" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 18);


Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("nl-NL")));
// Displays (8) aug, augustus
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("lv-LV")));
// Displays (8) Aug, augusts

Back to table

The "MM" Custom Format Specifier

The "MM" custom format specifier represents the month as a number from 01 through 12 (or from
1 through 13 for calendars that have 13 months). A single-digit month is formatted with a leading
zero.
The following example includes the "MM" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 1, 2, 6, 30, 15);

Console.WriteLine(date1.ToString("dd, MM",
CultureInfo.InvariantCulture));
// 02, 01

Back to table

The "MMM" Custom Format Specifier

The "MMM" custom format specifier represents the abbreviated name of the month. The localized
abbreviated name of the month is retrieved from
theDateTimeFormatInfo.AbbreviatedMonthNames property of the current or specified culture.
The following example includes the "MMM" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15);

Console.WriteLine(date1.ToString("ddd d MMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Fri 29 Aug
Console.WriteLine(date1.ToString("ddd d MMM",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays ven. 29 août

Back to table

The "MMMM" Custom Format Specifier

The "MMMM" custom format specifier represents the full name of the month. The localized name
of the month is retrieved from the DateTimeFormatInfo.MonthNamesproperty of the current or
specified culture.
The following example includes the "MMMM" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy
DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15);

Console.WriteLine(date1.ToString("dddd dd MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Friday 29 August
Console.WriteLine(date1.ToString("dddd dd MMMM",
CultureInfo.CreateSpecificCulture("it-IT")));
// Displays venerdì 29 agosto

Back to table

The "s" Custom Format Specifier

The "s" custom format specifier represents the seconds as a number from 0 through 59. The result
represents whole seconds that have passed since the last minute. A single-digit second is formatted
without a leading zero.
If the "s" format specifier is used without other custom format specifiers, it is interpreted as the "s" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "s" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1 µ
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1.5 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1.5 µ

Back to table

The "ss" Custom Format Specifier


The "ss" custom format specifier (plus any number of additional "s" specifiers) represents the
seconds as a number from 00 through 59. The result represents whole seconds that have passed
since the last minute. A single-digit second is formatted with a leading zero.
The following example includes the "ss" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01 PM
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01 du.
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01.50 PM
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01.50 du.

Back to table

The "t" Custom Format Specifier

The "t" custom format specifier represents the first character of the AM/PM designator. The
appropriate localized designator is retrieved from
theDateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the
current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to
11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.99.
If the "t" format specifier is used without other custom format specifiers, it is interpreted as the "t" standard date
and time format specifier. For more information about using a single format specifier, see Using Single Custom
Format Specifiers later in this topic.
The following example includes the "t" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1 µ
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.InvariantCulture));
// Displays 6:9:1.5 P
Console.WriteLine(date1.ToString("h:m:s.F t",
CultureInfo.CreateSpecificCulture("el-GR")));
// Displays 6:9:1.5 µ

Back to table

The "tt" Custom Format Specifier

The "tt" custom format specifier (plus any number of additional "t" specifiers) represents the entire
AM/PM designator. The appropriate localized designator is retrieved from
the DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the
current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to
11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.99.
Make sure to use the "tt" specifier for languages for which it is necessary to maintain the distinction between
AM and PM. An example is Japanese, for which the AM and PM designators differ in the second character
instead of the first character.
The following example includes the "tt" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01 PM
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01 du.
date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500);
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01.50 PM
Console.WriteLine(date1.ToString("hh:mm:ss.ff tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01.50 du.

Back to table

The "y" Custom Format Specifier


The "y" custom format specifier represents the year as a one-digit or two-digit number. If the year
has more than two digits, only the two low-order digits appear in the result. If the first digit of a
two-digit year begins with a zero (for example, 2008), the number is formatted without a leading
zero.
If the "y" format specifier is used without other custom format specifiers, it is interpreted as the "y" standard
date and time format specifier. For more information about using a single format specifier, see Using Single
Custom Format Specifiers later in this topic.
The following example includes the "y" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(1, 12, 1);


DateTime date2 = new DateTime(2010, 1, 1);
Console.WriteLine(date1.ToString("%y"));
// Displays 1
Console.WriteLine(date1.ToString("yy"));
// Displays 01
Console.WriteLine(date1.ToString("yyy"));
// Displays 001
Console.WriteLine(date1.ToString("yyyy"));
// Displays 0001
Console.WriteLine(date1.ToString("yyyyy"));
// Displays 00001
Console.WriteLine(date2.ToString("%y"));
// Displays 10
Console.WriteLine(date2.ToString("yy"));
// Displays 10
Console.WriteLine(date2.ToString("yyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyyy"));
// Displays 02010

Back to table

The "yy" Custom Format Specifier

The "yy" custom format specifier represents the year as a two-digit number. If the year has more
than two digits, only the two low-order digits appear in the result. If the two-digit year has fewer
than two significant digits, the number is padded with leading zeros to produce two digits.
The following example includes the "yy" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(1, 12, 1);


DateTime date2 = new DateTime(2010, 1, 1);
Console.WriteLine(date1.ToString("%y"));
// Displays 1
Console.WriteLine(date1.ToString("yy"));
// Displays 01
Console.WriteLine(date1.ToString("yyy"));
// Displays 001
Console.WriteLine(date1.ToString("yyyy"));
// Displays 0001
Console.WriteLine(date1.ToString("yyyyy"));
// Displays 00001
Console.WriteLine(date2.ToString("%y"));
// Displays 10
Console.WriteLine(date2.ToString("yy"));
// Displays 10
Console.WriteLine(date2.ToString("yyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyyy"));
// Displays 02010

Back to table

The "yyy" Custom Format Specifier

The "yyy" custom format specifier represents the year with a minimum of three digits. If the year
has more than three significant digits, they are included in the result string. If the year has fewer
than three digits, the number is padded with leading zeros to produce three digits.
 Note
For the Thai Buddhist calendar, which can have five-digit years, this format specifier displays all
significant digits.
The following example includes the "yyy" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(1, 12, 1);


DateTime date2 = new DateTime(2010, 1, 1);
Console.WriteLine(date1.ToString("%y"));
// Displays 1
Console.WriteLine(date1.ToString("yy"));
// Displays 01
Console.WriteLine(date1.ToString("yyy"));
// Displays 001
Console.WriteLine(date1.ToString("yyyy"));
// Displays 0001
Console.WriteLine(date1.ToString("yyyyy"));
// Displays 00001
Console.WriteLine(date2.ToString("%y"));
// Displays 10
Console.WriteLine(date2.ToString("yy"));
// Displays 10
Console.WriteLine(date2.ToString("yyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyyy"));
// Displays 02010

Back to table

The "yyyy" Custom Format Specifier

The "yyyy" custom format specifier represents the year with a minimum of four digits. If the year
has more than four significant digits, they are included in the result string. If the year has fewer than
four digits, the number is padded with leading zeros to produce four digits.
 Note
For the Thai Buddhist calendar, which can have five-digit years, this format specifier displays a
minimum of four digits.
The following example includes the "yyyy" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(1, 12, 1);


DateTime date2 = new DateTime(2010, 1, 1);
Console.WriteLine(date1.ToString("%y"));
// Displays 1
Console.WriteLine(date1.ToString("yy"));
// Displays 01
Console.WriteLine(date1.ToString("yyy"));
// Displays 001
Console.WriteLine(date1.ToString("yyyy"));
// Displays 0001
Console.WriteLine(date1.ToString("yyyyy"));
// Displays 00001
Console.WriteLine(date2.ToString("%y"));
// Displays 10
Console.WriteLine(date2.ToString("yy"));
// Displays 10
Console.WriteLine(date2.ToString("yyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyyy"));
// Displays 02010
Back to table

The "yyyyy" Custom Format Specifier

The "yyyyy" custom format specifier (plus any number of additional "y" specifiers) represents the
year with a minimum of five digits. If the year has more than five significant digits, they are
included in the result string. If the year has fewer than five digits, the number is padded with
leading zeros to produce five digits.
If there are additional "y" specifiers, the number is padded with as many leading zeros as necessary to produce
the number of "y" specifiers.
The following example includes the "yyyyy" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = new DateTime(1, 12, 1);


DateTime date2 = new DateTime(2010, 1, 1);
Console.WriteLine(date1.ToString("%y"));
// Displays 1
Console.WriteLine(date1.ToString("yy"));
// Displays 01
Console.WriteLine(date1.ToString("yyy"));
// Displays 001
Console.WriteLine(date1.ToString("yyyy"));
// Displays 0001
Console.WriteLine(date1.ToString("yyyyy"));
// Displays 00001
Console.WriteLine(date2.ToString("%y"));
// Displays 10
Console.WriteLine(date2.ToString("yy"));
// Displays 10
Console.WriteLine(date2.ToString("yyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyy"));
// Displays 2010
Console.WriteLine(date2.ToString("yyyyy"));
// Displays 02010

Back to table

The "z" Custom Format Specifier

With DateTime values, the "z" custom format specifier represents the signed offset of the local
operating system's time zone from Coordinated Universal Time (UTC), measured in hours. It does
not reflect the value of an instance's DateTime.Kind property. For this reason, the "z" format
specifier is not recommended for use with DateTime values.
With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in
hours.
The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus
sign (-) indicates hours behind UTC. A single-digit offset is formatted without a leading zero.
If the "z" format specifier is used without other custom format specifiers, it is interpreted as a standard date and
time format specifier and throws a FormatException. For more information about using a single format specifier,
see Using Single Custom Format Specifiers later in this topic.
The following example includes the "z" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy

DateTime date1 = DateTime.UtcNow;


Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}",
date1));
// Displays -7, -07, -07:00

DateTimeOffset date2 = new DateTimeOffset(2008, 8, 1, 0, 0, 0,


new TimeSpan(6, 0, 0));
Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}",
date2));
// Displays +6, +06, +06:00

Back to table

The "zz" Custom Format Specifier

With DateTime values, the "zz" custom format specifier represents the signed offset of the local
operating system's time zone from UTC, measured in hours. It does not reflect the value of an
instance's DateTime.Kind property. For this reason, the "zz" format specifier is not recommended
for use with DateTime values.
With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in
hours.
The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus
sign (-) indicates hours behind UTC. A single-digit offset is formatted with a leading zero.
The following example includes the "zz" custom format specifier in a custom format string.
VB
C#
C++
F#
JScript
Copy
DateTime date1 = DateTime.UtcNow;
Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}",
date1));
// Displays -7, -07, -07:00

DateTimeOffset date2 = new DateTimeOffset(2008, 8, 1, 0, 0, 0,


new TimeSpan(6, 0, 0));
Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}",
date2));
// Displays +6, +06, +06:00

Back to table

C# DateTime Examples
You want to use
the DateTime t
ype in the C#
programming
language, and
also need
various methods
to find important
days, such as yesterday, tomorrow,
the first of the year, and the last
day. The DateTime type in the C#
language provides useful methods
and properties for computing these
values. This document introduces
several useful methods and shows
their output.

Use DateTime to
compute relative dates.
Create new DateTimes
with overloaded
constructors.
Review other DateTime
properties.

Constructor
For the DateTime type in the C#
programming language and .NET
Framework, you can use the instance
constructor with the 'new' operator
to instantiate a new DateTime
instance. Please note that the
arguments to the constructor must
match to a real date that occurred.
This example also shows how you
can write a DateTime to the console,
and also to how you can compare a
DateTime against the Today value.

--- Program that uses DateTime


constructor [C#] ---

using System;

class Program

static void Main()

// This DateTime is constructed


with an instance constructor.

// ... We write it to the console.

// ... If this is today, the second


line will be "True".

DateTime value = new


DateTime(2010, 1, 18);

Console.WriteLine(value);

Console.WriteLine(value ==
DateTime.Today);

}
--- Output of the program ---

The second line depends on the local


date on your computer.

1/18/2010 12:00:00 AM

True

Finding yesterday
Here we see how to subtract one day
from the current day. We do this by
adding -1 to the current day, which
is necessary because no "Subtract
Days" method is provided. An
extension method could help
depending on your style.

--- Program that uses DateTime [C#]


---

using System;

class Program

static void Main()

Console.WriteLine("Today: {0}",
DateTime.Today);

DateTime y = GetYesterday();

Console.WriteLine("Yesterday:
{0}", y);
}

/// <summary>

/// Gets the previous day to the


current day.

/// </summary>

static DateTime GetYesterday()

// Add -1 to now

return
DateTime.Today.AddDays(-1);

--- Output of the program ---

Today: 11/30/2008 12:00:00 AM

Yesterday: 11/29/2008 12:00:00 AM

Description. What the example


displays is the current day. Note that
the Console.WriteLine implicitly
converts the DateTime.Today
argument using its ToString()
method. XML comments are very
useful here because you may want to
put these methods in a helper class,
which would make them reusable
across projects. The example was
run on November 30, 2008. The
output will naturally vary depending
on the day you run it.
DateTime.Today is always set to the
machine's local time.

See DateTime Subtract Method.

Finding tomorrow
Here we see how you can add one
using the DateTime Add method to
figure out tomorrow. This is useful
for using date queries in databases,
as you usually have to select a range
of dates.

--- Program that uses AddDays [C#]


---

using System;

class Program

static void Main()

Console.WriteLine("Today: {0}",
DateTime.Today);

DateTime d = GetTomorrow();

Console.WriteLine("Tomorrow:
{0}", d);

/// <summary>

/// Gets the next day, tomorrow.

/// </summary>
static DateTime GetTomorrow()

return
DateTime.Today.AddDays(1);

--- Output of the program ---

Today: 11/30/2008 12:00:00 AM

Tomorrow: 12/1/2008 12:00:00 AM

Description. This method and the


previous ones are static methods
because they do not require state to
be saved. DateTime.Today is not an
instance of the class. DateTime.Add
uses offsets, meaning it accepts both
negative and positive numbers. Here
we literally go back in time.

Using XML comments. The XML


comments here again will be useful if
you need to use this method in many
places. XML comments are not
always useful for private methods.

First day in year


Here we see how you can use a
simple helper method to find the first
day in a year. We use an overloaded
method here, which can make usage
of the methods easier as there are
fewer method names. If you want
the current year, don't call the above
method with a parameter. The
DateTime parameter of the second
DateTime method above can be any
time in the required year. It could be
a better design to simply pass it the
year as an int.

--- Program that uses new DateTime


[C#] ---

using System;

class Program

static void Main()

Console.WriteLine("First day:
{0}",

FirstDayOfYear());

DateTime d = new
DateTime(1999, 6, 1);

Console.WriteLine("First day of
1999: {0}",

FirstDayOfYear(d));

/// <summary>

/// Gets the first day of the current


year.

/// </summary>

static DateTime FirstDayOfYear()


{

return
FirstDayOfYear(DateTime.Today);

/// <summary>

/// Finds the first day of year of the


specified day.

/// </summary>

static DateTime
FirstDayOfYear(DateTime y)

return new DateTime(y.Year, 1,


1);

--- Output of the program ---

First day: 1/1/2008 12:00:00 AM

First day of 1999: 1/1/1999 12:00:00 AM

Last day in year


Here we see how to find the last day
in any year. Note that leap years
make this more complicated, as
February may have 28 or 29 days.
Because of leap year, you cannot use
the length of the year as a constant.
We can find it programmatically
using the new DateTime constructor.
This method is ideal for when you
want to count days, as for a
database range query for a certain
year.

--- Program that uses new DateTime


[C#] ---

using System;

class Program

static void Main()

Console.WriteLine("Last day:
{0}",

LastDayOfYear());

DateTime d = new
DateTime(1999, 6, 1);

Console.WriteLine("Last day of
1999: {0}",

LastDayOfYear(d));

/// <summary>

/// Finds the last day of the year for


today.

/// </summary>

static DateTime LastDayOfYear()

{
return
LastDayOfYear(DateTime.Today);

/// <summary>

/// Finds the last day of the year for


the selected day's year.

/// </summary>

static DateTime
LastDayOfYear(DateTime d)

// 1

// Get first of next year

DateTime n = new
DateTime(d.Year + 1, 1, 1);

// 2

// Subtract 1 from it

return n.AddDays(-1);

--- Output of the program ---

Last day: 12/31/2008 12:00:00 AM

Last day of 1999: 12/31/1999 12:00:00


AM

Description. We see two overloaded


methods here, which can make the
calling conventions more natural and
easier to remember. Recall that
overloaded methods are inferred at
compile time, not runtime. It is much
better to use the new DateTime
constructor, rather than
DateTime.Parse to create new
DateTimes. This is both for
performance and for simplicity of
syntax.

Find time elapsed since


date
Here we mention that you can find
the "age" of a certain date, and how
long ago it was in time. You can do
this with DateTime.Subtract, which
will return a TimeSpan.

See Days Elapsed From DateTime.

DateTime methods
In this section, we look at methods
on the DateTime type specifically.
Here are my notes on the DateTime
methods that are useful. This is not
exhaustive, but complementary to
MSDN.

See FromOADate and Excel Dates.

See DateTime.Parse String Method.

See DateTime.ParseExact Usage.

See DateTime Format.

DateTime.Add
This requires a TimeSpan
to be received. You will
need to use the TimeSpan
constructor first.

DateTime.AddDays
Receives a positive or
negative double integer,
which adds or subtracts
days. We see examples in
this document.

DateTime.AddHours
DateTime.AddMilliseconds
DateTime.AddMinutes
DateTime.AddMonths
DateTime.AddSeconds
DateTime.AddYears
These are self-explanatory
and receive a positive or
negative double, for
adding or subtracting the
specified part of the
DateTime.

DateTime.AddTicks
One tick is considered one
millisecond. This method
might be useful when
used with
Environment.AddTicks.

DateTime.Compare
DateTime.CompareTo
These tell you whether
one date is bigger or
smaller than another.
Mainly used for sorting.
However, you don't need
to implement a custom
sort for DateTime
normally.

DateTime.DaysInMonth
Helper method that will
tell you how many days
are in a month. I haven't
used it but it is useful to
know about.

DateTime.Equals
This is the sample as
op_Equality, the ==
operator.

DateTime.FromBinary
DateTime.ToBinary
Parses or creates a binary
date. You may have a
binary date if you have
serialized a date to a file.
I haven't used these.

DateTime.FromFileTime
DateTime.FromFileTimeUt
c
DateTime.ToFileTime
DateTime.ToFileTimeUtc
Use these for when you
have file times you need
to convert. I haven't used
this.

DateTime.FromOADate
DateTime.ToOADate
Useful for converting Excel
dates to C# dates. May
also be useful for Visual
FoxPro or Microsoft
Access. I have used this
for
Microsoft.Office.Excel.Inte
rop.

DateTime.GetDateTimeFor
mats
This provides functionality
related to formatting. It is
overloaded and may be
helpful rarely.

DateTime.GetDaylightSavi
ngTime
Daylight saving time is
what we get for letting
our politicians pretend to
be scientists. Not useful in
Arizona.

DateTime.IsLeapYear
Leap years have 29 days
in February. Leap year is
here to make
programmers' lives hard
and has very little other
impact.

DateTime.Subtract
Takes away one DateTime
or TimeSpan from the first
one. This isn't as useful as
the Add methods, as you
must provide a more
complex parameter.

DateTime.ToLocalTime
Normally your dates will
be in the local time, but if
you acquire an external
DateTime, you can
convert it to the local
timezone with this.

DateTime.Parse
DateTime.ParseExact
DateTime.TryParse
DateTime.TryParseExact
You will need to consult
MSDN for information on
exactly what formats can
be parsed. If you have
lots of invalid data, use
TryParse, as it will capture
its exceptions and
improve performance.

DateTime.ToString
DateTime.ToLongDateStri
ng
DateTime.ToLongTimeStri
ng
DateTime.ToShortDateStri
ng
DateTime.ToLongTimeStri
ng
For these ToString
methods, it is best to
simply experiment to find
the one you like best or
that is most compatible. I
also recommend checking
MSDN's articles on
DateTime format strings.

Description of method
signatures. Many of the methods
above receive a double type, which is
a numeric type used similarly to int.
Double values can store decimal
places.

See Numeric Casts and Numbers.

DayOfWeek property
You can find more detailed
information on the DayOfWeek
property on the DateTime instance,
which allows you to determine if a
date is a Monday, Tuesday,
Wednesday, Thursday, Friday,
Saturday, or Sunday. Please see the
specific article.

See DayOfWeek Enum.

Properties
In this section, we look at properties
on the DateTime type. These
properties, also listed at the link to
MSDN above, are useful abstractions
for getting specific aspects of your
DateTime. This table contains my
notes and a few hints.

See DateTime.Now for Getting


Current Time.

DateTime.Date
This returns only the date
component of the
DateTime. It has the
"time value set to
12:00:00 midnight
(00:00:00)." From
DateTime.Date Property
(System) at MSDN.

DateTime.Day
DateTime.DayOfWeek
DateTime.DayOfYear
DateTime.Hour
DateTime.Millisecond
DateTime.Minute
DateTime.Month
DateTime.Second
DateTime.Ticks
DateTime.TimeOfDay
DateTime.Year
These return a component
of the time. Note that this
is not the interval since
any other date. They just
return the single part of
the date. For example,
Day returns "the day
component, expressed as
a value between 1 and
31." From DateTime.Day
Property (System) at
MSDN.

DateTime.Today
This returns "a DateTime
set to today's date, with
the time component set to
00:00:00." From
DateTime.Today Property
(System) at MSDN.

DateTime.Now
DateTime.UtcNow
These return the current
DateTime, with all of the
fields correctly filled in.
DateTime.Now is one of
the most common
properties to use.

DateTime.Kind
Returns a DateTimeKind. I
recommend checking
MSDN for all the specifics,
as they are not useful for
me to repeat here.

Null DateTime structs


The DateTime struct in the C#
programming language is a value
type and not a reference type and for
this reason you cannot use a null
DateTime. You can either use a
nullable DateTime class or simply use
the DateTime.MinValue value to
indicate an empty DateTime. You can
find more information on DateTime
structs and the null value here.

See DateTime.MinValue (Null).

S-ar putea să vă placă și