下一个3am发生的DateTime [英] DateTime of next 3am occurrence
问题描述
我确定这很简单,但是我有一个突然的心理障碍。
我试图获得一个DateTime对象,用于下一次3am的发生。例如,如果 DateTime.Now
是 16/7月/ 2009:12:04 pm
- 下一次发生3点$ 17/7月/ 2009:03:00
I'm sure this is very easy, but I've got a sudden mental block.
I'm trying to get a DateTime object for the next occurence of 3am. For example, if DateTime.Now
is 16/july/2009 : 12:04pm
- the next occurance of 3am would be 17/july/2009 : 03:00
但是,如果 DateTime.Now
是 17/7月/ 2009:01:00
那么下一次发生仍然是 17 / July / 2009:03 :00
(不是第二天)。
这是否有意义?
However, if DateTime.Now
was 17/july/2009 : 01:00
then the next occurence would still be 17/july/2009 : 03:00
(not the day after).
Does that make sense?
推荐答案
一个选项:
DateTime now = DateTime.Now;
DateTime today3am = now.Date.AddHours(3);
DateTime next3am = now <= today3am ? today3am : today3am.AddDays(1);
另一个:
DateTime now = DateTime.Now;
DateTime today = now.Date;
DateTime next3am = today.AddHours(3).AddDays(now.Hour >= 3 ? 1 : 0)
当然,这些都是在 local 的时候,这就意味着这个特定的猫的皮肤的很多方法:)
Lots of ways of skinning that particular cat :)
你不需要担心时区。如果你想获得时区,生活会变得更棘手...
This is all in local time of course, which means you don't need to worry about time zones. Life becomes trickier if you want to get time zones involved...
请注意,采取 DateTime.Now
一次,以避免在计算日期时滚过...
Note that it's a good idea to take DateTime.Now
once to avoid problems if the date rolls over while you're calculating...
这篇关于下一个3am发生的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!