Docsity

Dates and Times: Understanding DateTime, DateTimeOffset, and TimeSpan in C#, Slides of C Sharp Programming

Partial preview of the text

Download Dates and Times: Understanding DateTime, DateTimeOffset, and TimeSpan in C# and more Slides C Sharp Programming in PDF only on Docsity!

Dates and Times

Introduction to

Dates and Times (1)

 The DateTime data type is used to store dates and times  There is a date part  There is a time part  It’s granular to 100 ns  DateTimeOffset works like DateTime but stores a UTC offset  The TimeSpan data type is used to store a time interval like a stopwatch  You can perform arithmetic on dates and times

The DateTime Data Type (1)

 There constructors to create  A date (year, month, day)  A date and time (year, month, day, hours, minutes, seconds)  A flag indicating the time zone ( DateTimeKind )  Unspecified  UTC  Local

The DateTime Data Type (2)

 The value is stored as a 62-bit number  Number of elapsed ticks since 1/1/  2-bit enum containing the DateTimeKind  Local, UTC, OR neither  When compared, ticks are compared. The DateTimeKind is ignored

The DateTime Data Type

(Properties)

Year , Month , Day , Hour , Minute , Second give us the date and time parts  DayofWeek returns an enum  DayOfYear returns the value of the same name

The DateTimeOffset

Data Type

 Similar to the DateTime data type  The constructor takes a TimeSpan argument containing the UTC offset  Properties  Now gives us the current local time and UTC offset  UtcNow adds the UTC offset

Time Zones (2)

 The System.TimeZone class represents a time zone  CurrentTimeZone get the time zone of the local computer  StandardName returns the name of the time zone  DayligtName returns the name of the daylight time zone

Time Zones (3)

The TimeSpan Data Type

 The TimeSpan data type represents a time interval  Elapsed hours, minutes, seconds…  It’s much like a stopwatch  You can  Subtract two dates giving a TimeSpan  Add a timespan to a date giving a timespan  Add and subtract two timespans

TimeSpan Constructors

 The following constructors create a TimeSpan :

Date Arithmetic using

TimeSpans

 Add a TimeSpan to a date:

int hours, minutes, seconds; TimeSpan span = new TimeSpan(hours, minutes, seconds); currentDate = currentDate.Add(span);

 Subtract a TimeSpan from a date currentDate = currentDate.Subtract(span);