Composing a Date Value

Introduction

The DateTime.ToString() method supports various techniques to display a date value. To get the desired format, you must compose an expression with the appropriate letters and symbols.

Practical LearningPractical Learning: Introducing Date Values

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> Recent Projects and Solutions -> ...CountriesStatistics08

The Year of a Date Composition

To get a short date string, call a DateTime.ToString() method and pass the argument as M/d/yyyy. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
<h1>Date Values</h1>

@{
    DateTime date = new DateTime(2020, 10, 23);
}

<p>@date.ToString("M/d/yyyy")</p>
</body>
</html>

If you want to display the year with two digits, pass the year part with yy. Here is an example:

<!DOCTYPE html>
<html>
<head>
    <title>Exercise</title>
</head>
<body>
    <h1>Exercise</h1>

    @{
        DateTime dateHired = new DateTime(2019, 04, 08);

        string strDateHired = string.Format("The employee was hired on {0}",
                                            dateHired.ToString("M/d/yy"));
    }

    <p>@strDateHired</p>
</body>
</html>

The Day of a Date Composition

To display a day in a date value, pass at least one d in the composition. If you provide one d for the day, if the day is less than 10, it would display with one digit. If you want to display a leading 0, pass dd. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
    <h1>Date Values</h1>

    @{
        DateTime date = new DateTime(2020, 10, 23);
    }

    <p>@date.ToString("M/d/yy")</p>
    <p>@date.ToString("M/dd/yyyy")</p>
    <p>@date.ToString("M/dd/yy")</p>
    <p>@date.ToString("M/d/yyyy")</p>
</body>
</html>

This would produce:

Date and Time Values

The Month of a Date Composition

Tc control the month when composing a date format, you can provide at least one M. If you provide one M, if the month is between 1 and 9, it would display without a leading 0. If you want to display a leading 0, pass MM. Here are two examples:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
<h1>Date Values</h1>

@{
    DateTime date = new DateTime(2020, 10, 23);
}

<p>@date.ToString("MM/d/yy")</p>
<p>@date.ToString("MM/d/yyyy")</p>
</body>
</html>

If you want to display the short name of a month, specify its portion as MMM. In this case, you should provide the MMM between tw dashes, in which case the day would be on the left of the month and the year on the right. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
    <h1>Date Values</h1>

    @{
        DateTime date = new DateTime(2020, 06, 02);
    }

    <p>@date.ToString("d-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yyyy")</p>
</body>
</html>

This would produce:

Date and Time Values

As an option, you can write the parts separated by spaces and commas. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
    <h1>Date Values</h1>

    @{
        DateTime date = new DateTime(2020, 06, 02);
    }

    <p>@date.ToString("d-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yyyy")</p>
    <p>@date.ToString("MMM d, yyyy")</p>
    <p>@date.ToString("MMM dd, yyyy")</p>
</body>
</html>

To compose a long date format or one of its variants, pass the month part as MMMM. In this case, you should create the parts separated by spaces and commas. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Date Values</title>
</head>
<body>
    <h1>Date Values</h1>

    @{
        DateTime date = new DateTime(2020, 09, 02);
    }

    <p>@date.ToString("d-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yy")</p>
    <p>@date.ToString("dd-MMM-yyyy")</p>
    <p>@date.ToString("MMM d, yyyy")</p>
    <p>@date.ToString("MMM dd, yyyy")</p>
    <p>@date.ToString("MMMM d, yyyy")</p>
    <p>@date.ToString("MMMM dd, yyyy")</p>
</body>
</html>

This would produce:

The Default Date and Time Values

Practical LearningPractical Learning: Formatting a Date Display

  1. Change the code in the States.cshtml tab as follows:
    @{
        ViewBag.Title = "United Mexican States";
    }
    
    <h2>United Mexican States</h2>
    
    @{
        . . . No Change
    }
    
    @{ 
        int i = 0;
    }
    
    <table border="6" style="width: 700px" cellpadding="2" cellspacing="1">
        <tr>
            <td class="text-center">&nbsp;</td>
            <td>&nbsp;</td>
            <td colspan="2" class="text-center"><b>Area</b></td>
            <td colspan="2" class="text-center"><b>Admission to Federation</b></td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td class="text-center short-text">#</td>
            <td><b>State Name</b></td>
            <td class="text-center"><b>Sqr Kms</b></td>
            <td class="text-center"><b>Sqr Miles</b></td>
            <td class="text-center"><b>Date</b></td>
            <td class="text-center"><b>Order</b></td>
            <td><b>Capital</b></td>
        </tr>
        @while (i < dateOfAdmissionToFederation.Length)
        {
            <tr>
                <td class="text-center">@(i + 1)</td>
                <td>@states[i]</td>
                <td class="text-right">@areasSqrKms[i]</td>
                <td class="text-right">@areasSqrMiles[i]</td>
                <td class="text-center">@dateOfAdmissionToFederation[i].ToString("yyyy-MMM-dd")</td>
                <td class="text-center">@ordersOfAdmissionToFederation[i]</td>
                <td>@capitals[i]</td>
            </tr>
    
            i++;
        }
    </table>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Accessing the Members of an Array

  3. Close the browser and return to your programming environment

Getting the Month and Day

To get the name of a month and the year value of a DateTime object, both separated by an empty space, pass a single M (uppercase) as string to the ToString() method of a DateTime object. Here is an example:

@{
    DateTime date = new DateTime(2004, 10, 23);
    string strDate = date.ToString("M");
}

<p>Date and Time:  @date</p>
<p>Month and Year: @strDate</p>

This would produce:

Date and Time Values

To include a comma in the result, pass a single y (lowercase) as string to the ToString() method of a DateTime object. Here is an example:

@{
    DateTime date = new DateTime(2004, 10, 23);
    string strDate = date.ToString("y");
}

<p>Date and Time:  @date</p>
<p>Month and Year: @strDate</p>

This would produce:

Date and Time Values

Today's Date

The date that is currently on the computer is referred to as today's date. To let you get the current date of the computer, the DateTime structure is equipped with a read-only static property named Today:

public static DateTime Today { get; }

As you can see, this property produces a DateTime value. To retrieve any value (day, month, or year) from it, or to get its value any way you want, you can call any of the methods (ToLongDateString() or ToShortDateString()) or, by calling the Date.ToString(string) method, apply any of the formats we have seen so far. Here are examples:

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

<p>The traffic violation occurred on @DateTime.Today.ToString("d").</p>

@{
    string day = DateTime.Today.Day.ToString() + "th";

    if (DateTime.Today.Day == 1)
    {
        day = "1st";
    }
    else if (DateTime.Today.Day == 21)
    {
        day = "21st";
    }
    else if (DateTime.Today.Day == 2)
    {
        day = "2nd";
    }
    else if (DateTime.Today.Day == 22)
    {
        day = "22nd";
    }
    else if (DateTime.Today.Day == 3)
    {
        day = "3rd";
    }
    else if (DateTime.Today.Day == 23)
    {
        day = "23rd";
    }
}

<p>In summary, the traffic violation occurred on @DateTime.Today.ToString("dddd") the @day of @DateTime.Today.ToString("MMMM") in @DateTime.Today.ToString("yyyy") (the full date is @DateTime.Today.ToLongDateString()).</p>
</body>
</html>

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

Presenting Time Values

Adding Values to a Date

Introduction

To let you perform various types of operations on date values, the DateTime is equipped with various methods.

Practical LearningPractical Learning: Introducing Operations on Dates

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) and set the project Name to PayrollPreparation16
  3. Click OK
  4. In the New ASP.NET Web Applicationn dialog box, in the Tempates list, click the MVC icon and click OK
  5. In the Solution Explorer, expand Controllers and double-click HomeController.cs to open it
  6. Add the following method to the class:
    using System.Web.Mvc;
    
    namespace PayrollPreparation15.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult TimeSheet()
            {
                return View();
            }
        }
    }
  7. In the Solution Explorer, expand Views, right-click Home -> Add -> New Scaffolded Item...
  8. In the middle frame of hte Add Scaffold dialog box, click MVC 5 View
  9. Click Add
  10. Type TimeSheet as the name of the view
  11. Click Add
  12. Change the document as follows:
    @{
        ViewBag.Title = "Employee Time Sheet";
    }
    
    <h2>Employee Time Sheet</h2>
    
    @{ 
        string strWeek1Monday = string.Empty, strWeek2Monday = string.Empty;
        string strWeek1Tuesday = string.Empty, strWeek2Tuesday = string.Empty;
        string strWeek1Wednesday = string.Empty, strWeek2Wednesday = string.Empty;
        string strWeek1Thursday = string.Empty, strWeek2Thursday = string.Empty;
        string strWeek1Friday = string.Empty, strWeek2Friday = string.Empty;
        string strWeek1Saturday = string.Empty, strWeek2Saturday = string.Empty;
        string strWeek1Sunday = string.Empty, strWeek2Sunday = string.Empty;
    
        if (IsPost)
        {
            if (!string.IsNullOrEmpty(Request["StartDate"]))
            {
            
            }
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td style="width: 110px"><b>Start Date:</b></td>
                <td>@Html.TextBox("StartDate")</td>
                <td><input type="submit" name="btnGenerateDate" value="Generate Time Sheet Dates" /></td>
            </tr>
        </table>
        <hr />
        <table>
            <tr>
                <td style="width: 110px">&nbsp;</td>
                <td><b>Monday</b></td>
                <td><b>Tuesday</b></td>
                <td><b>Wednesday</b></td>
                <td><b>Thursday</b></td>
                <td><b>Friday</b></td>
                <td><b>Saturday</b></td>
                <td><b>Sunday</b></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@strWeek1Monday</td>
                <td>@strWeek1Tuesday</td>
                <td>@strWeek1Wednesday</td>
                <td>@strWeek1Thursday</td>
                <td>@strWeek1Friday</td>
                <td>@strWeek1Saturday</td>
                <td>@strWeek1Sunday</td>
            </tr>
            <tr>
                <td><b>Week 1:</b></td>
                <td>@Html.TextBox("Week1Monday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Tuesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Wednesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Thursday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Friday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Saturday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Sunday", "0.00", new { style = "width: 80px" })</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="5"><hr /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@strWeek2Monday</td>
                <td>@strWeek2Tuesday</td>
                <td>@strWeek2Wednesday</td>
                <td>@strWeek2Thursday</td>
                <td>@strWeek2Friday</td>
                <td>@strWeek2Saturday</td>
                <td>@strWeek2Sunday</td>
            </tr>
            <tr>
                <td><b>Week 1:</b></td>
                <td>@Html.TextBox("Week2Monday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Tuesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Wednesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Thursday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Friday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Saturday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Sunday", "0.00", new { style = "width: 80px" })</td>
            </tr>
        </table>
    }

Adding Years to a Date

To let you get a date a few years after a known date, the DateTime class is equipped with a method named AddYears. Its syntax is:

public DateTime AddYears(int years);

The argument passed to the method is the number of years. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>

@{
    DateTime dateOfBirth = new DateTime(2019, 5, 12);

    DateTime mjority = dateOfBirth.AddYears(18);
}

<p>Date of Birth: @dateOfBirth.ToLongDateString().</p>

<p>Anniversary: @mjority.ToLongDateString().</p>
</body>
</html>

This would produce:

Date and Time Values

Adding Months to a Date

To let you add a number of months to a date, the DateTime class is equipped with a method named AddMonths. Its syntax is:

public DateTime AddMonths(int months);

This method takes one argument as the number of months to be added. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>

@{
    int delay = 4; // months
    DateTime announcement = new DateTime(2019, 5, 14);

    DateTime graduation = announcement.AddMonths(delay);
}

<p>Today, @announcement.ToLongDateString(), we announce that the graduation ceremony will be held on @graduation.ToLongDateString(), which gives you @delay months to get prepared.</p>
</body>
</html>

This would produce:

Date and Time Values

Adding Days to a Date Value

With the DateTime structure, you can add some days to an existing date. To support this, the DateTime structure is equipped with a method named AddDays. Its syntax is:

public DateTime AddDays(int days);

Here is an example of calling this method:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>

@{
    int length = 6; // days
    DateTime announcement = new DateTime(2019, 5, 12);

    DateTime vacationEnd = announcement.AddDays(length);
}

<p>Your @length-day cruise will start on @announcement.ToLongDateString() and end on @vacationEnd.ToLongDateString(). Enjoy!!!</p>
</body>
</html>

This would produce:

Date and Time Values

Subtracting from a Date Value

Introduction

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

Subtracting Years from a Date

To get the date that corresponds to some previous years from a known date, you can call the DateTime.AddYears() method but pass a negative value. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<h1>Exercise</h1>

@{
    int age = 26; // years
    DateTime birthday = new DateTime(2019, 5, 12);

    DateTime dateofBirth = birthday.AddYears(-age);
}

<p>Let me understand this, today @birthday.ToLongDateString() you are @age years old. So you were born on @dateofBirth.ToLongDateString()? Enjoy!!!</p>
</body>
</html>

This would produce:

Date and Time Values

Subtracting Months from a Date

To find a date that occurs a number of months behind, call the DateTime.AddMonths method with a negative argument. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Cable Company</title>
</head>
<body>
    <h1>Cable Company</h1>

@{
    int months = 3;
    DateTime cutOff = new DateTime(2019, 5, 8);

    DateTime previous = cutOff.AddMonths(-months);
}

<p>We have not received any payment from you since @previous.ToLongDateString(). That is, your current bill is @months months late.</p>
<p>Your service will be cut off today @cutOff.ToLongDateString() until you make your full payment!!!</p>
</body>
</html>

This would produce:

Date and Time Values

Subtracting Days from a Date Value

If you want to subtract some days from a date, pass a negative value to the DateTime.AddDays() method. This method is able to figure out the year before, the month before, the day before, the day after, the month after, and the year after the designated date. Here is an example of calling this method:

<!DOCTYPE html>
<html>
<head>
<title>Research & Development</title>
</head>
<body>
    <h1>Research & Development</h1>

@{
    int days = 38;
    DateTime medEnd = new DateTime(2019, 8, 12);

    DateTime medStart = medEnd.AddDays(-days);
}

<p>Your medication trial period started on @medStart.ToLongDateString(). Its was meant to last @days days until @medEnd.ToLongDateString().</p>
<p>We can't provide any more medication until you do a follow-up with our research department.</p>
</body>
</html>

This would produce:

Date and Time Values

Logical Operations on Dates

Using the logical operators we reviewed for primitive types, you can compare the values of dates for equality, differences, lower or greater values. To support these operations, the DateTime structure has the logical operators configured appropriately.

To compare two dates, 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

Practical LearningPractical Learning: Adding Days to a Date Value

  1. Change the document as follows:
    @{
        ViewBag.Title = "Employee Time Sheet";
    }
    
    <h2>Employee Time Sheet</h2>
    
    @{ 
        string strWeek1Monday = string.Empty, strWeek2Monday = string.Empty;
        string strWeek1Tuesday = string.Empty, strWeek2Tuesday = string.Empty;
        string strWeek1Wednesday = string.Empty, strWeek2Wednesday = string.Empty;
        string strWeek1Thursday = string.Empty, strWeek2Thursday = string.Empty;
        string strWeek1Friday = string.Empty, strWeek2Friday = string.Empty;
        string strWeek1Saturday = string.Empty, strWeek2Saturday = string.Empty;
        string strWeek1Sunday = string.Empty, strWeek2Sunday = string.Empty;
    
        if (IsPost)
        {
            if(!string.IsNullOrEmpty(Request["StartDate"]))
            {
                DateTime dtStartDate = Request["StartDate"].AsDateTime();
    
                strWeek1Monday = dtStartDate.ToShortDateString();
                strWeek1Tuesday = dtStartDate.AddDays(1).ToShortDateString();
                strWeek1Wednesday = dtStartDate.AddDays(2).ToShortDateString();
                strWeek1Thursday = dtStartDate.AddDays(3).ToShortDateString();
                strWeek1Friday = dtStartDate.AddDays(4).ToShortDateString();
                strWeek1Saturday = dtStartDate.AddDays(5).ToShortDateString();
                strWeek1Sunday = dtStartDate.AddDays(6).ToShortDateString();
                strWeek2Monday = dtStartDate.AddDays(7).ToShortDateString();
                strWeek2Tuesday =  dtStartDate.AddDays(8).ToShortDateString();
                strWeek2Wednesday = dtStartDate.AddDays(9).ToShortDateString();
                strWeek2Thursday = dtStartDate.AddDays(10).ToShortDateString();
                strWeek2Friday = dtStartDate.AddDays(11).ToShortDateString();
                strWeek2Saturday = dtStartDate.AddDays(12).ToShortDateString();
                strWeek2Sunday = dtStartDate.AddDays(13).ToShortDateString();
            }
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td style="width: 110px"><b>Start Date:</b></td>
                <td>@Html.TextBox("StartDate")</td>
                <td><input type="submit" name="btnGenerateDate" value="Generate Time Sheet Dates" /></td>
            </tr>
        </table>
        <hr />
        <table>
            <tr>
                <td style="width: 110px">&nbsp;</td>
                <td><b>Monday</b></td>
                <td><b>Tuesday</b></td>
                <td><b>Wednesday</b></td>
                <td><b>Thursday</b></td>
                <td><b>Friday</b></td>
                <td><b>Saturday</b></td>
                <td><b>Sunday</b></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@strWeek1Monday</td>
                <td>@strWeek1Tuesday</td>
                <td>@strWeek1Wednesday</td>
                <td>@strWeek1Thursday</td>
                <td>@strWeek1Friday</td>
                <td>@strWeek1Saturday</td>
                <td>@strWeek1Sunday</td>
            </tr>
            <tr>
                <td><b>Week 1:</b></td>
                <td>@Html.TextBox("Week1Monday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Tuesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Wednesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Thursday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Friday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Saturday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week1Sunday", "0.00", new { style = "width: 80px" })</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="5"><hr /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@strWeek2Monday</td>
                <td>@strWeek2Tuesday</td>
                <td>@strWeek2Wednesday</td>
                <td>@strWeek2Thursday</td>
                <td>@strWeek2Friday</td>
                <td>@strWeek2Saturday</td>
                <td>@strWeek2Sunday</td>
            </tr>
            <tr>
                <td><b>Week 1:</b></td>
                <td>@Html.TextBox("Week2Monday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Tuesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Wednesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Thursday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Friday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Saturday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Week2Sunday", "0.00", new { style = "width: 80px" })</td>
            </tr>
        </table>
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Adding Days to a Date Value

  3. In the top text box, type a date such as 07/01/2018

    Adding Days to a Date Value

  4. Click the button:

    Adding Days to a Date Value

  5. Close the browser and return to your programming environment
  6. Close your programming environment

Previous Copyright © 2001-2019, FunctionX Next