-4

I have an instance of DateTime that I get from my database, I want to subtract it from DateTime.Now and find out if 4 hours were passed. How do I do that?

Also when should i use DateTime.UTCNow or DateTimeOffset

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
Matrix001
  • 1,272
  • 6
  • 30
  • 51

5 Answers5

6

You can use the subtraction operator to get a TimeSpan:

private static readonly TimeSpan MinimumTime = TimeSpan.FromHours(4);

...

if ((dateFromDatabase - DateTime.Now) > MinimumTime)
{
    ...
}

As for whether you need UTCNow or Now... it will depend on what happens to time zones when you fetch the data from the database. DateTime is not terribly clear on this front :(

If you can fetch the value as a DateTimeOffset to start with, then you can use DateTimeOffset.Now instead and it should be simpler to work out any time zone issues.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I have a site that is in my local language (not english), so i dont think i will have the issue of TimeZones – Matrix001 Jun 28 '11 at 10:04
  • @Matrix001: Languages and time zones are very different things. It will depend on how the database stores (and returns) `DateTime` values etc. Don't assume it'll be okay just because everything is in one time zone... – Jon Skeet Jun 28 '11 at 10:05
  • So if it stores 14:00, i might end up with 16:00? Does it depend on where the database is located? I read that DateTime is sensitive to regional changes while DateTimeOffset isnt.. so how can i get in trouble for using DateTime? – Matrix001 Jun 28 '11 at 11:50
  • @Matrix001: It will depend on your database, and potentially the schema. You can get in trouble using DateTime because a DateTime *can* be UTC or it *can* be "local". It's basically unclear. A DateTimeOffset *always* represents an instant in time. – Jon Skeet Jun 28 '11 at 13:01
4

DateTime.Subtract

First Google hit..

ba__friend
  • 5,783
  • 2
  • 27
  • 20
  • 1
    Also a duplicate: http://stackoverflow.com/questions/6304514/how-to-subtract-datetime-values-and-get-the-time – rciq Jun 28 '11 at 09:53
  • 1
    Except that that's not actually the idiomatic way to do it, as you probably want to use the subtraction *operator*. – Jon Skeet Jun 28 '11 at 09:53
  • Sure but my point was more that he could typed 2 words into the address bar of his browser to get his answer. ;) Also the operator-style is described on that page. :) – ba__friend Jun 28 '11 at 09:55
3

Try this:

bool fourHoursPassed = date.AddHours(4) < DateTime.Now;

or this to actually perform a subtraction:

bool fourHoursPassed = (DateTime.Now - date).TotalHours > 4;
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
1

DateTime.Subtract

or

DateTime myDateTime = someValue; TimeSpan ts = DateTime.Now -myDateTime; if(ts.Hours>=4) { doSomething(); }

Hope it helps.

Miran
  • 85
  • 7
1

DateTime dt = new DateTime(2011, 07, 10); DateTime dob = new DateTime(1987, 07, 10);

You can simply subtract as: TimeSpan age = dt - dob;