Subtract Hours from a Date

  • Thread starter Thread starter Lee
  • Start date Start date
L

Lee

Hi All,

I have a datetime field and want to subtract 24 (or any other number of)
hours from it.

How would I go about this?

Thanks

Lee
 
Lee,

What you want to do is create an instance of the TimeSpan class, and
then subtract that from your DateTime instance. You can also call the
AddDays, AddHours, etc, etc methods on the DateTime instance, passing
negative numbers to subtract the values from the DateTime. Note that these
methods return a new DateTime instance with the modified value, as opposed
to modifying the current value.

Hope this helps.
 
Lee said:
I have a datetime field and want to subtract 24 (or any other number of)
hours from it.

How would I go about this?

Use DateTime.AddHours (-24) - and don't forget that that doesn't change
the value you call it on, it just returns a new DateTime.
 
Thanks, that was the right direction, This is the what I did to get it
working

DateTime dt =
DateTime.Now.Add(System.TimeSpan.FromHours(System.Convert.ToDouble((intHours*-1))));
 
Lee said:
Thanks, that was the right direction, This is the what I did to get it
working

DateTime dt =
DateTime.Now.Add(System.TimeSpan.FromHours(System.Convert.ToDouble((i
ntHours*-1))));

That seems a very longwinded way of doing:

DateTime dt = DateTime.Now.AddHourse (-intHours);
 
Back
Top