User Tools

Site Tools


notes:csharp:datetime

DateTime in C#

Instantiating

// Construct a date by specifying elements of the date and time value.
DateTime d = new DateTime(2008, 12, 31, 17, 30, 0); // year, month, day, hour, minutes, seconds
 
// Assign a date returned by a property.
DateTime d1 = DateTime.Now;    // 2016-03-11 11:40:00 AM
DateTime d2 = DateTime.UtcNow; // 2016-03-11 4:40:00 PM (+5h in my time zone)
DateTime d3 = DateTime.Today;  // 2016-03-11 12:00:00 AM
 
// Call the DateTime's default constructor.
DateTime d = new DateTime(); // 01/01/0001 00:00:00
bool b = d.Equals(DateTime.MinValue); // b == true

Parsing

Use Parse, ParseExact, TryParse, or TryParseExact methods to convert a string to a DateTime value.

using System.Globalization;
...
// Parse the string representation of a date and time value.
DateTime d = DateTime.ParseExact(
    "2008/12/31 17:30:00",
    "yyyy/MM/dd HH:mm:ss",
    CultureInfo.InvariantCulture);
 
// Parse the string representation of a date matching it to particular formats.
string[] formats = { "M/dd/yyyy", "MM/dd/yyyy", "M/d/yyyy", "MM/d/yyyy" };
DateTime d1 = DateTime.ParseExact("5/24/2015", formats, null, DateTimeStyles.None);
DateTime d2 = DateTime.ParseExact("  05/04/2015  ", formats, null, DateTimeStyles.AllowWhiteSpaces);
DateTime d3 = DateTime.ParseExact("5/4/  2015", formats, null, DateTimeStyles.AllowInnerWhite);
 
// Determine the custom format strings that correspond to a standard format string.
// Output: dd/MM/yyyy, yyyy-MM-dd, dd/MM/yy, d/M/yy, yy-MM-dd, etc.
foreach (string s in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d'))
    Console.WriteLine(s);
 
// Parse the string representation of a date matching to a standard format string .
DateTime d = DateTime.ParseExact("31/12/2015", "d", CultureInfo.CurrentCulture); // dd/MM/yyyy

Formatting

Use the overloads of the ToString method.

DateTime d = new DateTime(2008, 12, 31, 17, 30, 0);
 
// The current culture's short date and long time.
string s = d.ToString(); // 31/12/2008 5:30:00 PM
 
// A specific culture's short date and long time.
string s = d.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("pl-PL")); // 2008-12-31 17:30:00
 
// A culture-independent's short date and long time.
string s = d.ToString(System.Globalization.CultureInfo.InvariantCulture); // 12/31/2008 17:30:00
 
// A format defined by a standard or custom format specifier and the current culture.
string s = d.ToString("F"); // December 31, 2008 5:30:00 PM
 
// A round-trip date/time pattern (ISO 8601).
string s = d.ToString("O"); // 2008-12-31T17:30:00.0000000
 
// A format defined by a standard or custom format specifier and a specific culture.
string s = d.ToString("F", new System.Globalization.CultureInfo("pl-PL")); // 31 grudnia 2008 17:30:00
-or-
System.Globalization.DateTimeFormatInfo info = new System.Globalization.CultureInfo("pl-PL").DateTimeFormat;
string s = d.ToString("F", info); // 31 grudnia 2008 17:30:00

Note that all standard format specifiers are one character long. Any specifiers longer than that are considered to be custom format specifiers. To differentiate between a standard specifier and a one-character long custom specifier, include the % character before the custom specifier (or include a space before or after the specifier):

// A standard format specifier.
string s = d.ToString("y", System.Globalization.CultureInfo.InvariantCulture); // 2008 December
 
// A custom format specifier.
string s = d.ToString("%y", System.Globalization.CultureInfo.InvariantCulture); // 8
string s = d.ToString(" y", System.Globalization.CultureInfo.InvariantCulture); //  8

Operations

DateTime d = new DateTime(2015, 11, 27, 17, 45, 0);
 
// Obtain the first day in a year.
DateTime firstDay = new DateTime(d.Year, 1, 1); // 2015-01-01
 
// Obtain the last day in a year.
DateTime lastDay = (new DateTime(d.Year + 1, 1, 1)).AddDays(-1); // 2015-12-31
 
// Obtain the number of days in February.
int daysInFebruary = DateTime.DaysInMonth(d.Year, 2); // 28
 
// Obtain the current week number.
DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo;
Calendar cal = info.Calendar;
int weekNumber = cal.GetWeekOfYear(DateTime.Now, info.CalendarWeekRule, info.FirstDayOfWeek);
 
// Add one hour and 15 minutes.
DateTime d2 = d.Add(new TimeSpan(1, 15, 0)); // 2015-11-27 7:00:00 PM
 
// Compare time components only. TimeOfDay returns a TimeSpan interval that 
// represents a fraction of the day that has elapsed since midnight.
bool differentTime = (d.TimeOfDay != d2.TimeOfDay);

Ticks

Use the following methods when working with ticks:

  • TimeSpan.TicksPerDay
  • TimeSpan.TicksPerHour
  • TimeSpan.TicksPerMinute
  • TimeSpan.TicksPerSecond
  • TimeSpan.TicksPerMillisecond
DateTime d = new DateTime(2015, 11, 27, 17, 45, 0);
long ticks = 60000000; // represents 6 seconds in ticks
 
// Add the number of seconds represented by ticks to the Second component of a DateTime value.
DateTime d2 = d.AddSeconds(d.Second + ticks / TimeSpan.TicksPerSecond); // 2015-11-27 5:45:06 PM

DateTimeKind

The DateTime's Kind property provides information about the time zone to which that date and time belongs:

  • DateTimeKind.Local represents the local time
  • DateTimeKind.Utc represents Coordinated Universal Time (UTC)
  • DateTimeKind.Unspecified represents an unspecified time

MSDN: When saving or sharing DateTime data, UTC should be used and the DateTime value's Kind property should be set to DateTimeKind.Utc.

DateTime d = new DateTime(2015, 12, 31, 17, 30, 0);
DateTimeKind kind = d.Kind; // DateTimeKind.Unspecified
 
DateTime d = new DateTime(2015, 12, 31, 17, 30, 0, DateTimeKind.Utc);
DateTimeKind kind = d.Kind; // DateTimeKind.Utc
notes/csharp/datetime.txt · Last modified: 2016/11/22 by admin