开发者

How do I subtract one DateTime from another?

开发者 https://www.devze.com 2023-03-15 17:27 出处:网络
I have an instance of DateTime that I get from my databas开发者_开发技巧e, I want to subtract it from DateTime.Now and find out if 4 hours were passed. How do I do that?

I have an instance of DateTime that I get from my databas开发者_开发技巧e, 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


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.


DateTime.Subtract

First Google hit..


Try this:

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

or this to actually perform a subtraction:

bool fourHoursPassed = (DateTime.Now - date).TotalHours > 4;


DateTime.Subtract

or

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

Hope it helps.


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消