Comparing Dates in ASP.NET


The question was about comparing dates in two textboxes. How do you get the values out in hours and minutes.
 
The comparison is quite easy. You can do it, rather simply, with the following:
 
    protected void CompareButton_Click(object sender, EventArgs e)
    {
       
DateTime time1 = DateTime.Parse(TextBox1.Text);
       
DateTime time2 = DateTime.Parse(TextBox2.Text);

        TimeSpan ts = time2 – time1;

        int hours = ts.Hours + (ts.Days * 24);
       
int minutes = ts.Minutes;
    }

 
This makes two dangerous assumptions, however:
  1. The input is valid. Considering rule #1 of web forms is "Never trust user input", this is a dangerous assumption.
  2. Time2 is larger than Time1. If this is not the case, all of your numbers will be negative

Let’s solve these problems:

Problem 1: Never Trust User Input

To solve the first problem, we can simply do a check on the values. This is done using the TryParse method on the DateTime struct:

    protected void CompareButton_Click(object sender, EventArgs e)
    {
       
DateTime time1, time2;
       
TimeSpan ts;

        bool time1Okay = DateTime.TryParse(TextBox1.Text, out time1);
       
bool time2Okay = DateTime.TryParse(TextBox2.Text, out time2);

        if ((time1Okay) && (time2Okay))
        {
            ts = time2 – time1;
        }
       
else
        {
           
//Alert user
        }

        int hours = ts.Hours + (ts.Days * 24);
       
int minutes = ts.Minutes;
    }

We now have a mechanism to alert the user something is wrong, provided we fill in the else.

Problem 2: Assume time2 greater than time1

We can attack this from two directions. The first is to correct negatives when we find them:

        if (hours < 0)
            hours = 0 – hours;

        if (minutes < 0)
            minutes = 0 – minutes;

The second is to Compare whether time1 is less than or not:

            if (DateTime.Compare(time1, time2) < 0)
                ts = time2 – time1;
           
else
                ts = time1 – time2;

Either will work, although the second version is a bit more "proper". This leads us to the following complete routine:

    protected void CompareButton_Click(object sender, EventArgs e)
    {
       
DateTime time1, time2;
       
TimeSpan ts;

        bool time1Okay = DateTime.TryParse(TextBox1.Text, out time1);
       
bool time2Okay = DateTime.TryParse(TextBox2.Text, out time2);

        if ((time1Okay) && (time2Okay))
        {
           
if (DateTime.Compare(time1, time2) < 0)
                ts = time2 – time1;
           
else
                ts = time1 – time2;
        }
       
else
        {
           
//Alert user
        }

        int hours = ts.Hours + (ts.Days * 24);
       
int minutes = ts.Minutes;
    }

Other Options

For those who like to run through calculations, you can also calculate the hours and minutes like so:

            double totalSeconds = ts.TotalSeconds;
           
double workingMinutes = (totalSeconds / 60);
           
int seconds = (int)(workingMinutes – (int)workingMinutes);
           
int hours = (int)(workingMinutes / 60);
           
int minutes = (int)(workingMinutes – (hours *60));

It ends up with the same result. You can also go from the opposite direction, like so:

            double totalHours = ts.TotalHours;
           
int hours = (int)totalHours;
           
double workingMinutes = (totalHours – hours) * 60;
           
int minutes = (int)workingMinutes;
           
int seconds = (int)((workingMinutes – minutes) * 60);

The problem here is you will end up with a rounding error in many cases.

Why would someone want to calculate when they can simply pull from the TimeSpan struct? I have no clue. Just for giggles?

Peace and Grace,
Greg

Advertisements

One Response to Comparing Dates in ASP.NET

  1. Kelly says:

    This was very useful thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: