问题描述
如何检查日期是否天生就是明天?
How can I check to see if a date is inherently TOMORROW?
我不想在今天这样的日期添加小时或任何东西,因为如果今天已经 22:59
,添加太多会转到第二天,如果时间 12:00 $则添加太少c $ c>明天会错过。
I don't want to add hours or anything to a date like today, because if today is already 22:59
, adding too much would go over to the day after, and adding too little if the time is 12:00
would miss tomorrow.
如何检查两个 NSDate
并确保一个是等价的明天换另一个?
How can I check two NSDate
s and ensure that one is the equivalent of tomorrow for the other?
推荐答案
使用您可以提取日/月/ year组件从代表今天的日期开始,忽略小时/分钟/秒组件,添加一天,并重建与明天相对应的日期。
Using NSDateComponents
you can extract day/month/year components from the date representing today, ignoring the hour/minutes/seconds components, add one day, and rebuild a date corresponding to tomorrow.
所以想象你想要恰好在当前日期添加一天(包括保持小时/分钟/秒inf ormation与now日期相同),你可以使用 dateWithTimeIntervalSinceNow
将timeInterval 24 * 60 * 60秒添加到now,但它更好(和DST一样) -proof etc)使用 NSDateComponents
这样做:
So imagine you want to add exactly one day to the current date (including keeping hours/minutes/seconds information the same as the "now" date), you could add a timeInterval of 24*60*60 seconds to "now" using dateWithTimeIntervalSinceNow
, but it is better (and DST-proof etc) to do it this way using NSDateComponents
:
NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setDay:1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];
但如果你想生成明天午夜对应的日期,您可以只检索现在代表的日期的月/日/年组件,不带小时/分/秒零件,然后再添加1天,然后重建日期:
But if you want to generate the date corresponding to tomorrow at midnight, you could instead just retrieve the month/day/year components of the date representing now, without hours/min/secs part, and add 1 day, then rebuild a date:
// Decompose the date corresponding to "now" into Year+Month+Day components
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
PS:您可以在。
P.S.: You can read really useful advice and stuff about date concepts in the Date and Time Programming Guide, especially here about date components.
这篇关于目标C - 从今天(明天)开始第二天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!