iOS和寻找明天 [英] iOS and finding Tomorrow

查看:86
本文介绍了iOS和寻找明天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查看日期是否固有地为TOMORROW?

How can I check to see if a date is inherently TOMORROW?

我不想像今天一样添加小时或任何日期,因为如果今天已经是 22:59 ,添加太多会过去一天,如果时间 12:00 会错过明天。

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 NSDates and ensure that one is the equivalent of tomorrow for the other?

推荐答案

使用 NSDateComponents ,您可以从中提取日/月/年组件日期代表今天,忽略小时/分钟/秒组件,添加一天,重建对应于明天的日期。

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.

想象一下,当前日期(包括保持小时/分钟/秒信息与现在日期相同),您可以使用 dateWithTimeIntervalSinceNow 向now添加24 * 60 * 60秒的timeInterval $ c>,但是使用 NSDateComponents 这样做是更好的(和DST-proof等):

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:您可以在日期和时间编程指南,特别是这里关于日期组件

这篇关于iOS和寻找明天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆