DateTime Calculations

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

I have an ASP.NET form(using C#) with several text boxes and when the user
places a date in the first textbox and clicks a button, I would like to
populate the remaining textboxes with various dates subtracted from the date
in the first textbox - any suggestions? I do know that the datetime class
has a subtract method, but I'm not sure how to use it. Incidentally I'm
using ASP.NET 2005 and obviously a beginner - please help!

Thanks,
Mike
 
Mike said:
I have an ASP.NET form(using C#) with several text boxes and when the user
places a date in the first textbox and clicks a button, I would like to
populate the remaining textboxes with various dates subtracted from the date
in the first textbox - any suggestions? I do know that the datetime class
has a subtract method, but I'm not sure how to use it. Incidentally I'm
using ASP.NET 2005 and obviously a beginner - please help!

DateTime oneDate = DateTime.Parse(myTextBox.Value);

// also look at TryParse for error checking when the user enters an
// invalid date.

DateTime otherDate = oneDate.AddDays(-1);

// Also:

otherDate = oneDate - TimeSpan.FromDays(1);

// etc...

The Subtract method is overloaded, and is a static way of calling the
'-' operator (which is also overloaded). Subtracting a DateTime from
another DateTime results in a TimeSpan, which represents the interval.
Subtracting a TimeSpan from a DateTime results in another DateTime.

TimeSpan doesn't work directly with units larger than days because of
variable month lengths. Instead, use 30 days, 60 days, whatever, etc.

-- Barry
 
Mike,

This is the thing you ^could^ do in ASP.NET, but don't want to. You
will want to do these kinds of calcs on the client side, so you would write
javascript code to be an event handler for the textbox, and then set the
dates when the textbox changes.

Here is a reference for the date functions that you will probably use in
your client-side code:

http://www.comptechdoc.org/independent/web/cgi/javamanual/javadate.html

Hope this helps.
 
Back
Top