A Date/Time Value

Introduction

The date and time are considered as one unit because they practically occur alongside. In other words, a time doesn't mean much if the date that time occurs is not taken into consideration. Most operations on date values are influenced by time. As a matter of fact, the DateTime structure always considers both the date and the time for its values.

The combined value of the date and time is made of two sections. The first section represents the date and the second section represents the time. The date part can use any of the valid formats of a date value. The time part uses one of the formulas of a time. Both sections are separated by an empty space.

The Default Date and Time

As you may know already, the primary way to declare a variable for a date and/or a time is to use the default constructor of the DateTime structure. Such a variable represents the January 1st, 0001 at midnight.

As we saw when studying time value, the following constructor of the DateTime structure can be used to create a value that represents both the date and the time value:

public DateTime(int year, int month, int day,
		        int hour, int minute, int second);

Requesting a Date and Time

Probably the easiest way to request a date and time from the user is to create a text box in a webpage. You can add some text to indicate how the user should provide the values. This can be done as follows:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
    <h1>Traffic Tickets</h1>

    <form name="TrafficTickets">
        <table>
            <tr>
                <td><label for="violationPeriod">Violation Period (MM/DD/YYYY HH:MM):</label></td>
                <td><input type="text" id="violationPeriod" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

This would produce:

Requesting a Date and Time Combination

Otherwise, you can add a placeholder in a text box.

Displaying a Date/Time Value

To display a date/time value in a webpage, you can precede the name of a DateTimevariable or a date/time value with @. You can display such a value as a static text in an HTML tag or in a control (such as a text box) for its value.

Formatting Date and Time Combinations

With a date/time value produced from a DateTime object, you can use the formats we have reviewed to create your own date, in the sequences of your choice, such as a time preceding a date, a value providing only the month and the minutes, etc.

Primary Characteristics of Date and Time Values

The Current Date and Time

To let you get the current date and time, the DateTime structure is equipped with aread-only static property named Now:

public static DateTime Now { get; }

This property holds the year, the month, the day, the name of the day, the hour, the minute, and the second. Here is an example of accessing it:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

<form name="TrafficTickets">
        <table>
            <tr>
                <td><label for="violationPeriod">Violation Period:</label></td>
                <td><input type="text" id="violationPeriod" value="@DateTime.Now" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

Here is an example of what the above code would produce:

Requesting a Date and Time Combination

From the DateTime.Now, if you want to get the current date, you can call either the DateTime.ToLongDateString() or the DateTime.ToShortDateString() methods. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

<p>The traffic violation occurred on @DateTime.Now.ToLongDateString() (that is @DateTime.Now.ToShortDateString()).</p>
</body>
</html>

Here is an example of what the above code would produce:

Requesting a Date and Time Combination

As an alternative, you can use any of the available formats for date values. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{ 
    string day = string.Empty;

    if(DateTime.Now.Day == 1)
    {
        day = "1st";
    }
    else if (DateTime.Now.Day == 21)
    {
        day = "21st";
    }
    else if (DateTime.Now.Day == 2)
    {
        day = "2nd";
    }
    else if (DateTime.Now.Day == 22)
    {
        day = "22nd";
    }
    else if (DateTime.Now.Day == 3)
    {
        day = "3rd";
    }
    else if (DateTime.Now.Day == 23)
    {
        day = "23rd";
    }
    else
    {
        day = DateTime.Now.Day.ToString() + "th";
    }
}
<p>The traffic violation occurred on @DateTime.Now.ToString("dddd") the @day of @DateTime.Now.ToString("MMMM") in @DateTime.Now.ToString("yyyy") (or more preciselly at @DateTime.Now.ToString("d")).</p>
</body>
</html>

Here is an example of what the above code would produce:

Requesting a Date and Time Combination

If you want to get the current time, you can call either the DateTime.ToLongTimeString() or the DateTime.ToShortTimeString() methods. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

<p>The traffic violation occurred on @DateTime.Now.ToLongDateString() at @DateTime.Now.ToShortTimeString() (or more preciselly at @DateTime.Now.ToLongTimeString()).</p>
</body>
</html>

Here is an example of what the above code would produce:

Presenting Time Values

The Minimum Date/Time Value

The lowest date and time values that a DateTime object can hold is January 1st, 0001 at 00:00:00. This value is represented by the MinValue constant member of the DateTime structure:

public static readonly DateTime MinValue;

As you can see, this field holds an object of type DateTime. As a result, you can use any of the methods on it to get the desired value. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>
<p>The lowest value of our calendar is @DateTime.MinValue.</p>
<p>Our default calendar started on @DateTime.MinValue.ToLongDateString() at @DateTime.MinValue.ToLongTimeString().</p>
</body>
</html>

This would produce:

Presenting Time Values

The Maximum Date/Time Value

The highest date and time that a DateTime object can hold in the structure is called MaxValue:

public static readonly DateTime MaxValue;

The DateTime value of this field is set to December 31, 9999 at 23:59:59. Once again, you can call any DateTime method to get the value or format you want.

Primary Operations on Date and Time Values

Introduction

The DateTime structure is equipped with methods to perform various types of operations on date and time values. To give you the ability to perform hours, minutes, and seconds-related operations, the TimeSpan structure is equipped with the following constructor:

public TimeSpan (int hours, int minutes, int seconds);

To let you add a value a number to a date/time value, the DateTime structure is equipped with a method named Add. Its syntax is:

public DateTime Add (TimeSpan value);

This method takes a TimeSpan object as argument and returns a DateTime object with updated values.

Adding Hours

To add a number of hours to a date/time value, use the TimeSpan constructor that takes three arguments. Pass an integral value for the first argument and pass the other two arguments 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
    <title>Traffic Tickets</title>
</head>
<body>
    <h1>Traffic Tickets</h1>

    @{
        TimeSpan ts = new TimeSpan(5, 0, 0);
        DateTime violationDate = new DateTime(2019, 5, 12, 6, 28, 55);

        DateTime registrationDate = violationDate.Add(ts);
    }

    <p>The traffic violation occurred on @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

    <p>The infraction was checked on @registrationDate.ToShortDateString() at @registrationDate.ToShortTimeString().</p>
</body>
</html>

This would produce:

Adding Hours to a Date/Time Value

To support the addition of hours, the DateTime structure is equipped with a method named AddHours. Its synbtax is:

public DateTime AddHours (double value);

This method takes the number of hours as argument. It produces a new date and time value. If the argument is kind of low, both dates might be the same just occurring at different times. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    DateTime violationDate = new DateTime(2019, 5, 12, 6, 28, 55);

    DateTime registrationDate = violationDate.AddHours(5);
}

<p>The traffic violation occurred on @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>The infraction was checked on @registrationDate.ToShortDateString() at @registrationDate.ToShortTimeString().</p>
</body>
</html>

If the argument is high enough, the new value may occur on the next day or a few days later. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    DateTime violationDate = new DateTime(2019, 5, 30, 21, 28, 55);

    DateTime registrationDate = violationDate.AddHours(65);
}

<p>The traffic violation occurred on @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>The infraction was checked on @registrationDate.ToShortDateString() at @registrationDate.ToShortTimeString().</p>
</body>
</html>

This would produce:

Adding Hours to a Date/Time Value

Adding Minutes to a Date/Time Value

To add a number of minutes to a date/time value, you have many options. To add some minutes to the hour of a date/time value, use the TimeSpan constructor that takes three arguments. Pass the first argument as 0, the second with the number of minutes, and the third argument as 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    TimeSpan ts = new TimeSpan(0, 7, 0);
    DateTime recordingTime = new DateTime(2019, 5, 8, 10, 28, 55);

    DateTime endTime = recordingTime.Add(ts);
}

<p>The violation recording started on @recordingTime.ToLongDateString() at @recordingTime.ToLongTimeString().</p>

<p>The violation recording ended on @endTime.ToLongDateString() at @endTime.ToShortTimeString().</p>
</body>
</html>

This would produce:

Adding Hours to a Date/Time Value

To let you add some minutes to a date/time value, the DateTime structure is equipped with a method named AddMinutes. Its syntax is:

public DateTime AddMinutes (double value);

If the argument is less than 60, its number of minutes would be added to the hour of the date/time that called it. The date of the result may be the same as that of the variable. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    DateTime recordingTime = new DateTime(2019, 5, 8, 10, 28, 55);

    DateTime endTime = recordingTime.AddMinutes(7);
}

<p>The violation recording started on @recordingTime.ToLongDateString() at @recordingTime.ToLongTimeString().</p>

<p>The violation recording ended on @endTime.ToLongDateString() at @endTime.ToShortTimeString().</p>
</body>
</html>

Adding Hours and Minutes

To add hours and minutes to a date/time value, if you are using the three-argument TimeSpan constructor, pass the desired number of hours for the first argument, the number of minutes for the second argument, and the third argument as 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    TimeSpan ts = new TimeSpan(16, 7, 0);
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 52);

    DateTime inspection = violationDate.Add(ts);
}

<p>Violation Type: Red Light - Right Turn</p>

<p>Traffic Violation Date: @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>Inspection Period @inspection.ToLongDateString() at @inspection.ToLongTimeString().</p>
</body>
</html>

This would produce:

Adding Hours to a Date/Time Value

You might have notice that the argument of the DateTime.AddHours() method is a double-precision number. If you pass it as an integer, only a number of hours would be added to its DateTime variable. If you want to add some hours and minutes, pass the argument as a floating-point number. In that case, the integral part would represent the hours and the fractional part would be the minutes. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 26);

    DateTime registrationDate = violationDate.AddHours(28.36);
}

<p>The traffic violation occurred on @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>The infraction was checked on @registrationDate.ToShortDateString() at @registrationDate.ToShortTimeString().</p>
</body>
</html>

This would produce:

Adding Hours to a Date/Time Value

Adding Seconds to a Date/Time Value

To add seconds to a date/time value, declare a TimeSpan variable using the constructor with three arguments. Pass the first two arguments as 0 and the third as the desired number of seconds. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    int recordingLength = 16;
    TimeSpan ts = new TimeSpan(0, 0, recordingLength);
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 52);

    DateTime endRecording = violationDate.Add(ts);
}

<p>Violation Type: Stop Sign</p>

<p>Traffic Violation Date: @violationDate.ToLongDateString().</p>

<p>The traffic camera started recording at @violationDate.ToLongTimeString().</p>
<p>The camera recorded the incident for @recordingLength seconds.</p>
<p>The camera stopped recording at @endRecording.ToLongTimeString().</p>
</body>
</html>

This would produce:

Adding Seconds to a Date/Time Value

As another option to add some seconds to a date/time value, the DateTime structure is equipped with a method named AddSeconds. Its syntax is:

public DateTime AddSeconds (double value);

When calling this method, you can pass the number of seconds as argument. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    int recordingLength = 16;
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 52);

    DateTime endRecording = violationDate.AddSeconds(recordingLength);
}

<p>Violation Type: Stop Sign</p>

<p>Traffic Violation Date: @violationDate.ToLongDateString().</p>

<p>The traffic camera started recording at @violationDate.ToLongTimeString().</p>
<p>The camera recorded the incident for @recordingLength seconds.</p>
<p>The camera stopped recording at @endRecording.ToLongTimeString().</p>
</body>
</html>

Adding Minutes and Seconds

The argument to the DateTime.Add​Minutes() is a double number. If you pass a natural number, only the minutes are added. If you want to add the minutes and seconds, pass the argument as a floating point number. The integral part would represent the minutes. If that number is less than 60, only the minutes would be added. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    DateTime violationDate = new DateTime(2019, 5, 12, 11, 47, 52);

    DateTime endRecording = violationDate.AddMinutes(24.43);
}

<p>Violation Type: Speed</p>

<p>The traffic camera started recording on @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>
<p>The camera stopped recording on @violationDate.ToLongDateString() at @endRecording.ToLongTimeString().</p>
</body>
</html>

This would produce:

Adding Seconds to a Date/Time Value

Adding Days

To assist you in adding days to a date/time value, the TimeSpan structure is equipped with the following constructor:

public TimeSpan (int days, int hours, int minutes, int seconds);

To simply add days, pass its number as the first argument and pass the other arguments as 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    TimeSpan ts = new TimeSpan(8, 0, 0, 0);
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 52);

    DateTime processing = violationDate.Add(ts);
}

<p>Violation Type: Red Light - Right Turn</p>

<p>Traffic Violation Date: @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>The infraction was processed on @processing.ToLongDateString().</p>
</body>
</html>

This would produce:

Adding Seconds to a Date/Time Value

In the same way, to add days and time parts to a date/time value, pass the other arguments to this constructor.

As an alternative, to add days to a date/time object, you can use the constructor that takes three arguments. Pass the first argument as the number of days times 24 and pass the other arguments as 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Tickets</title>
</head>
<body>
<h1>Traffic Tickets</h1>

@{
    TimeSpan ts = new TimeSpan(8 * 24, 0, 0); // 8 * 24 = 192
    DateTime violationDate = new DateTime(2019, 5, 12, 10, 17, 52);

    DateTime processing = violationDate.Add(ts);
}

<p>Violation Type: Red Light - Right Turn</p>

<p>Traffic Violation Date: @violationDate.ToLongDateString() at @violationDate.ToLongTimeString().</p>

<p>The infraction was processed on @processing.ToLongDateString().</p>
</body>
</html>

Subtracting Numbers from a Date/Time Value

Subtracting a Time Span Value

To find a date or time that occurs prior to a date or time of your choice, you have many options. As you may know already, the Add-related methods of the DateTime structure can be used to either add or subtract a value.

To let you subtract a value from a date or a time, the DateTime structure is equipped with an overloaded method named Subtract. This method comes in two versions. One of them takes a TimeSpan argument. Its syntax is:

public DateTime Subtract (TimeSpan value);

To use this method, create a TimeSpan value that contains the number(s) you want to subtract. Pass it as argument to the DateTime.Subtract() method.

Subtracting Hours

To find a date/time that occurs prior to a certain date, you can call the DateTime.AddHours() method with a negative numbers. The compiler would do the necesary calculations and find the corresponding full date. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>GPS Report</title>
</head>
<body>
    <h1>GPS Report</h1>

@{
    int hours = 66;
    DateTime currentDrivingTime = new DateTime(2019, 8, 12, 16, 17, 39);

    DateTime startDrivingTime = currentDrivingTime.AddHours(-hours);
}

<p><b>GPS Announcement</b>: Starting on @startDrivingTime.ToLongDateString() at @startDrivingTime.ToShortTimeString() till now (@currentDrivingTime.ToLongDateString() at @currentDrivingTime.ToShortTimeString()), you have been on the road for @hours hours.</p>
</body>
</html>

This would produce:

Date and Time Values

As an alternative, call the DateTime.Subtract() method that takes a TimeSpan as argument. When using the TimeSpan constructor that takes three arguments, pass the number of hours as the first argument and pass the other two arguments as 0. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>GPS Report</title>
</head>
<body>
    <h1>GPS Report</h1>

@{
    int hours = 66;
    TimeSpan ts = new TimeSpan(hours, 0, 0);
    DateTime currentDrivingTime = new DateTime(2019, 8, 12, 16, 17, 39);

    DateTime startDrivingTime = currentDrivingTime.Subtract(ts);
}

<p><b>GPS Announcement</b>: Starting on @startDrivingTime.ToLongDateString() at @startDrivingTime.ToShortTimeString() till now (@currentDrivingTime.ToLongDateString() at @currentDrivingTime.ToShortTimeString()), you have been on the road for @hours hours.</p>
</body>
</html>

Subtracting Days and Time from a Date

To find a date that occurs some days and/or hours prior to a certain date/time, you can call the DateTime.Subtract() method that takes a TimeSpan argument. You can use the TimeSpan constructor that takes three or four arguments. If you are using the one with four arguments, pass the first argument as the number of days. Pass the other arguments for the number of hours, the number of minutes, and the number of seconds.

Comparing Date/Time Values

The DateTime is overloaded with the necessary operators to compare date/time values such as to find out whether two periods occur at the exact same time or onoe of them occurs before another.

To compare two date/time values, apply the desired Boolean operator the same way you would proceed for two variables of primitive types. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Dates Comparisons</title>
</head>
<body>
<h1>Dates Comparisons</h1>

@{
    DateTime startDate = new DateTime(1988, 10, 6);
    // This will be used to add 8 days to the previous date
    DateTime endDate = startDate.AddDays(8);
}

<p>Starting Date: @startDate</p>
<p>Ending Date:   @endDate</p>

@if (startDate < endDate)
{
    <p>@startDate occurs before @endDate</p>
}
</body>
</html>

This would produce:

Date and Time Values

-------------------------------

The Time of Day of a DateTime Value

DateTime structure is equipped with a property named TimeOfDay. This property produces the time value of an existing DateTime object. Here is an example of using it:

@{
    DateTime time = new DateTime(2002, 4, 22, 16, 8, 44);
}

<p>Date and Time: @time</p>
<p>Time of Day:   @time.TimeOfDay</p>

This would produce:

Date and Time Values

Converting a Time Value to a String

If you have a DateTime object, you can convert it to a String value. To make this operation possible, the DateTime structure overrides the ToString() method. The default version of this method takes no argument and it simply creates a string out of a time value. Here is an example:

@{
    DateTime time = new DateTime(2002, 4, 22, 16, 8, 44);
    string strTime = time.ToString();
}

<p>Date and Time (DateTime): @time
<p>Date and Time(String): @strTime

This would produce:

Date and Time Values

structure has another overloaded version of the ToString() method that takes as argument a String value. Its syntax is:

public string ToString(string format);

Like dates, time values follow some rules:

Time

 The characters used to create a time format are:


Previous Copyright © 2001-2019, FunctionX Next