Working with Dates

In addition to using strings, you often need to handle dates and moments in time. To accomplish this, the .NET Framework 4.6 provides the System.DateTime value type.


MinValue and MaxValue

Being a value type, System.DateTime has two shared fields: MinValue and MaxValue. These store the minimum accepted date and the maximum date, respectively. The minimum date is 01/01/0001 00:00:00 a.m., and maximum date is 12/31/9999 11:59:59 p.m.


Creating Dates

The Visual Basic grammar offers the Date keyword, which is a lexical representation of the System.DateTime object, so you can use either Date or System.DateTime. For consistency, we use the Date reserved keyword, but keep in mind that this keyword creates (or gets a reference to) an instance of the System.DateTime type. Working with dates is an easy task. You can create a new date by creating an instance of the DateTime class:

Dim myBirthDate As New Date(1977, 5, 10)

The constructor has several overloads, but the most common is the preceding one, where you can specify year, month, and day. For example, such values could be written by the user and then converted into a DateTime object. Another common situation in which you need to create a date is for storing the current system clock date and time. This can be easily accomplished using the DateTime.Now property, as follows:

Dim currentDate As Date = Date.Now

Such code produces the following sample result:

12/26/2014 11:35:35 PM

When you get an instance of a DateTime, you can retrieve a lot of information about it. For example, consider the following code and especially pay attention to the comments:

'Creates a new date; May 10th 1977, 8.30 pm
Dim myBirthDate As New Date(1977, 5, 10,
                            20, 30, 0)
'In 1977, May 10th was Tuesday
Console.WriteLine(myBirthDate.DayOfWeek.
                  ToString)
'8.30 pm
Console.WriteLine("Hour: {0}, Minutes: {1}",
                  myBirthDate.Hour,
                  myBirthDate.Minute)
'Is the date included within the Day Light Saving Time period?
Console.WriteLine("Is Day light saving time: {0}",
                  myBirthDate.IsDaylightSavingTime.
                  ToString)
'Is leap year
Console.WriteLine("Is leap: {0}",
                  Date.IsLeapYear(myBirthDate.Year).
                  ToString)

The code first creates the following date, representing my birth date: 5/10/1977 8:30:00 p.m. Then it retrieves some information, such as the name of the day of the week (represented by the DayOfWeek enumeration), the hours, the minutes (via the Hour and Minute integer properties), and the specified date within Daylight Saving Time. The DateTime object also exposes a shared method named IsLeapYear that can establish whether the specified year is a leap year. In our example, the year is not passed directly but is provided via the Year property of the myBirthDate instance. The following is the result of the code:

Tuesday
Hour: 20, Minutes: 30
Is Day light saving time: True
Is leap: False

Finally, you can declare dates with the date literals. The following is an example of how you can customize the date format:

Dim customDate As Date = #5/25/2015 8:00:00 PM#

Visual Basic 2015 adds support for these year-first date literals, which allow you to use the year as the first part of a date. Because of this addition, you can now create a date like this:

Dim customDate As Date = #2015/12/26 11:00:00 PM#

You can also create a date literal based on a 24-hour clock, like this:

Dim customDate As Date = #2015/12/26 23:00:00 #

Converting Strings into Dates

It is not unusual to ask a user to provide a date within an application. Typically, this is accomplished via the user interface and, if you do not provide a specific user control (such as the WPF DatePicker or the Win Forms DateTimePicker) for selecting dates in a graphical fashion, such input is provided in the form of a string. Because of this, you need a way of converting the string into a date, so that you can then manipulate the user input as an effective DateTime object (unless the string is invalid; then you need validation). To accomplish this kind of conversion, the System.DateTime class provides two methods that you already saw when we discussed value types: Parse and TryParse. For example, consider the following code, which receives an input by the user and attempts to convert the input into a DateTime object:

Sub ParsingDates()
    Console.WriteLine("Please specify a date:")
    Dim inputDate As Date
    Dim result As Boolean = Date.TryParse(Console.ReadLine, inputDate)
    If result = False Then
        Console.WriteLine("You entered an invalid date")
    Else
        Console.WriteLine(inputDate.DayOfWeek.ToString)
    End If
End Sub

The TryParse method receives the string to convert as the first argument (which in this case is obtained by the Console window) and the output object passed by reference (inputDate); it returns True if the conversion succeeds or False if it fails. The conversion succeeds if the input string format is accepted and recognized by the DateTime type. If you run this code and enter a string in the format 1977/05/10, the conversion succeeds because this format is accepted by DateTime. You can then manipulate the new date as you like. (In the preceding example, the code shows the day of the week for the specified date, which in my example is Tuesday.)


Tip

In many cases you work with data from a database. The ADO.NET engine and layered technologies, such as LINQ, map dates from databases directly into a System.DateTime object so that you will be able to work with and manipulate such objects from and to data sources.


Formatting Dates

You need to present dates for several scenarios, and you might be required to perform this task in different ways. Fortunately, System.DateTime provides many ways of formatting dates. The easiest way is to invoke the ToString method, which accepts an argument that enables you to specify how a date must be presented. For example, consider the following code snippet, which writes the current date in both the extended (D) and short (d) date formats:

Console.WriteLine(DateTime.Now.ToString("D"))
Console.WriteLine(DateTime.Now.ToString("d"))

This code produces the following output:

Saturday, December 27, 2014
12/27/2014

The result is based on the regional and culture settings of your system. Table 4.9 summarizes symbols you can use with the ToString method.

Image

TABLE 4.9 Date Formatting Symbols with ToString

ToString also recognizes date literals. The following is an example of how you can customize and write a date:

Console.WriteLine(Date.Today.ToString("dd/MM/yyyy"))

This code prints the current date in the day/month/year format. System.DateTime provides a plethora of other useful methods you can use for formatting dates. Such methods also return different data types, depending on the scenario in which they are used. Table 4.10 summarizes the most important methods, and you can inspect them at any time with IntelliSense and the Object Browser.

Image

TABLE 4.10 Useful Methods for System.DateTime

The following code snippet uses all the preceding methods to demonstrate how the output differs depending on the method:

Console.WriteLine("Local time: {0}", Date.Now.ToLocalTime)
Console.WriteLine("Long date: {0}", Date.Now.ToLongDateString)
Console.WriteLine("Short date: {0}", Date.Now.ToShortDateString)
Console.WriteLine("Long time: {0}", Date.Now.ToLongTimeString)
Console.WriteLine("Short time: {0}", Date.Now.ToShortTimeString)
Console.WriteLine("Universal time: {0}", Date.Now.
                  ToUniversalTime.ToString)
Console.WriteLine("File time: {0}", Date.Now.
                  ToFileTime.ToString)
Console.WriteLine("File time UTC: {0}", Date.Now.
                  ToFileTimeUtc.ToString)
Console.WriteLine("OLE Automation date: {0}", Date.Now.
                  ToOADate.ToString)

The preceding code produces the following result, which you can compare with the methods described in Table 4.9:

Local time: 05/28/2012 19:27:22

Local time: 12/27/2014 18:46:50
Long date: Saturday, December 27, 2014
Short date: 27/12/2014
Long time: 18:46:50
Short time: 18:46
Universal time: 27/12/2014 17:46:50
File time: 130641760107079387
File time UTC: 130641760107089384
OLE Automation date: 42000,7825313542

Subtracting Dates and Adding Time to Time

It’s not unusual to need to know the amount of time spent between two dates. The System.DateTime enables you to find this by invoking a Subtract method, which returns a System.TimeSpan value. For example, consider the following code, which subtracts one date from another one:

Dim birthDate As Date = New Date(1977, 5, 10, 20, 30, 0)
Dim secondDate As Date = New Date(1990, 5, 11, 20, 10, 0)
Dim result As System.TimeSpan = secondDate.Subtract(birthDate)
'In days
Console.WriteLine(result.Days)
'In "ticks"
Console.WriteLine(result.Ticks)

You can subtract two DateTime objects and get a result of type TimeSpan (discussed next). You can then get information on the result, such as the number of days that represent the difference between the two dates or the number of ticks. The previous code produces the following result:

4748
4103124000000000

You can also add values to a date. For example, you can edit a date by adding days, hours, minutes, seconds, or ticks or by incrementing the year. Consider the following code snippet:

Dim editedDate As Date = birthDate.AddDays(3)
editedDate = editedDate.AddHours(2)
editedDate = editedDate.AddYears(1)
Console.WriteLine(editedDate)

This code adds three days and two hours to the date and increments the year by one unit. In the end, it produces the following output:

5/13/1978 10:30:00 PM

You can use negative numbers to subtract values from a single date, and you end up with a Date object instead of TimeSpan, as with Subtract. For instance, the following code subtracts a day from the date represented by the birthDate variable:

'Returns 05/09/1977
Dim result As Date = birthDate.AddDays(-1)

Dates are important and, although they allow you to work with time, too, the .NET Framework provides an important structure that is specific for representing pieces of time: System.TimeSpan.


Operators

You can use standard operators such as the addition and subtraction operators when working with both DateTime and TimeSpan objects. This is possible because both objects overload the standard operators. Overloading operators is discussed in Chapter 11.


The DateTimeOffset Structure

The .NET Framework exposes another structure for working with dates: System.DateTimeOffset. This object behaves like System.DateTime, but it is all about the Coordinated Universal Time (UTC) standard. The DateTimeOffset object has almost the same members of the DateTime class, except that it does not expose methods for conversions to different date/time formats. This is because the purpose of DateTimeOffset is to record the exact date, time, and time zone when an event occurred. Following are examples of this structure:

Dim dateOffset As DateTimeOffset = DateTimeOffset.Now
'Print the specified date in the UTC standard's format
Console.WriteLine(dateOffset.UtcDateTime)
'Print the hh:mm:ss:mmss time in the current instance
Console.WriteLine(dateOffset.TimeOfDay.ToString)

'Create a new DateTimeOffset
Dim myDate As New DateTimeOffset(2015, 1, 18, 10, 0, 0, Nothing)

To understand where using DateTimeOffset is a more appropriate choice, you can refer to the following summary:

Image If your business logic needs to record the time and date and time zone (or at least the time zone offset) at which an event occurred, then you should use DateTimeOffset.

Image If your business logic needs to record the time and date but does not need to record the time zone, then DateTime is a perfectly fine choice.

Image If every date and time in your business logic is in UTC, then you could invoke the DateTime.ToUniversalTime method on a date; this records exactly the same information as if you had a DateTimeOffset with its Offset set to 0h00.

The DateTimeOffset object is also very important when building Windows Store apps because built-in user controls that work with dates require objects of type DateTimeOffset instead of DateTime. The structure exposes a property called Date, which returns a DateTime representation of the current instance. DateTimeOffset is not new in the .NET Framework 4.6, but this version adds support to conversions to Unix time representation via the ToUnixTimeMilliseconds and ToUnixTimeSeconds methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.23.147