Date and Time
The DateTime Type
The
DateTime
Type C# has built-in support for dates and timesThis type can be used to represent a date and time, and it provides access to the system clock
The type also supports many operations that can make it easy to work with dates and times
The following block demonstrates some DateTime
operations:
The DateTime.Now
and DateTime.Today
properties are static, means you can access them without having an instance of a DateTime
Formatting Dates and Times
There are many ways to display dates and times. Times can be represented using 12-hour AM/PM style times, or using 24-hour format.
In formatting operations, custom date and time format strings can be used with the ToString
method of a date and time instance.
The following example illustrates this:
Getting to Parts of Dates and Times
DateTime type has many properties you can use to access different individual components of the date or time, such as the month, day, year, hour, minute, etc. The following sample demonstrates some of these properties:
Calculating Durations Between DateTimes
Sometimes it can be useful to think about the difference between two times, or the duration of an event. For instance, you could calculate how many days are left in the year. To do so, you would need to determine the first day of the next year, and then compare that to today. The following code shows how to do this:
This produces a new type called a TimeSpan
, which is used to represent a span of time, or a duration.
TimeSpan
provides many ways to represent its value, the TotalDays
property will show how many full days the TimeSpan
includes.
Exercise
Write a program that accepts a birth date ( dd/MMM/yyyy
) and calculates how many days old the person with that birth date is currently.
Hint: Use Parse()
method of DateTime
class
Expectation:
Last updated