This example shows how to format DateTime using String.Format method. All formatting can be done
also using DateTime.ToString method.
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
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#]
[C#]
// 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"
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First
column contains format specifiers for the String.Format method.
[C#]
========================
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.
using System;
class Program
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.
using System;
class Program
2 27 11:48 09
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.
using System;
class Program
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"));
d 2/27/2009
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
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.
using System;
class Program
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());
ToLongTimeString 12:16:59 PM
ToShortDateString 2/27/2009
ToShortTimeString 12:16 PM
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.
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.
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.
class Program
Console.WriteLine(now.ToString("ddd"));
now = now.AddDays(1);
Thu
Fri
Sat
Sun
Mon
Tue
Wed
using System;
class Program
Console.WriteLine(now.ToString("dddd"));
now = now.AddDays(1);
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.
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.
using System;
class Program
Console.WriteLine(now.ToString("tt "));
now = now.AddHours(12);
PM
AM
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.
using System;
class Program
{
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("y "));
Console.WriteLine(now.ToString("yy"));
Console.WriteLine(now.ToString("yyyy"));
09
2009
2009
02009
Other Versions
• 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.
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
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
• 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
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.
Defined by
Standard
DateTimeFormatInfo.InvariantInfo Custom format string
format 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;
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
Back to table
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
Back to table
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
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
Back to table
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
Back to table
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
Back to table
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
Back to table
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
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
Back to table
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
Back to table
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
Back to table
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
Back to table
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
Back to table
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
Back to table
Property Description
Back to table
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
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
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
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.)
Parse(String) Converts the specified string representation of a date and time
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.
Converts the specified string representation of a date and time
ParseExact(String, String to its DateTime equivalent using the specified array of formats,
[], IFormatProvider, culture-specific format information, and style. The format of
DateTimeStyles) 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.
ToString() Converts the value of the current DateTime object to its
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.
Inequality Determines whether two specified instances of DateTime are
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
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.
• 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
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
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
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.
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;
DateTime d1 = DateTime.Now;
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0
Other Versions
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
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;
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
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 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
Console.WriteLine(date1.ToString("dd, MM",
CultureInfo.InvariantCulture));
// 02, 01
Back to table
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 (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
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
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 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
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 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
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 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 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 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 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
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 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
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
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 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 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 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 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 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
Back to table
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
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 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
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
Back to table
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 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 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
Back to table
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
Console.WriteLine(date1.ToString("dd, MM",
CultureInfo.InvariantCulture));
// 02, 01
Back to table
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
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 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
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 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 (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 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 (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 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
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
Back to table
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
Back to table
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
Back to table
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
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
Back to table
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
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.
using System;
class Program
Console.WriteLine(value);
Console.WriteLine(value ==
DateTime.Today);
}
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.
using System;
class Program
Console.WriteLine("Today: {0}",
DateTime.Today);
DateTime y = GetYesterday();
Console.WriteLine("Yesterday:
{0}", y);
/// <summary>
/// </summary>
// Add -1 to now
return DateTime.Today.AddDays(-
1);
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.
using System;
class Program
Console.WriteLine("Today: {0}",
DateTime.Today);
DateTime d = GetTomorrow();
Console.WriteLine("Tomorrow:
{0}", d);
/// <summary>
return
DateTime.Today.AddDays(1);
using System;
class Program
Console.WriteLine("First day:
{0}",
FirstDayOfYear());
DateTime d = new
DateTime(1999, 6, 1);
Console.WriteLine("First day of
1999: {0}",
FirstDayOfYear(d));
/// <summary>
/// </summary>
static DateTime FirstDayOfYear()
return
FirstDayOfYear(DateTime.Today);
/// <summary>
/// </summary>
static DateTime
FirstDayOfYear(DateTime y)
using System;
class Program
Console.WriteLine("Last day:
{0}",
LastDayOfYear());
DateTime d = new
DateTime(1999, 6, 1);
Console.WriteLine("Last day of
1999: {0}",
LastDayOfYear(d));
/// <summary>
/// </summary>
return
LastDayOfYear(DateTime.Today);
/// <summary>
/// </summary>
static DateTime
LastDayOfYear(DateTime d)
// 1
DateTime n = new
DateTime(d.Year + 1, 1, 1);
// 2
// Subtract 1 from it
return n.AddDays(-1);
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.
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.
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.
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.
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.
Lebih dari sekadar dokumen.
Temukan segala yang ditawarkan Scribd, termasuk buku dan buku audio dari penerbit-penerbit terkemuka.
Batalkan kapan saja.