比如我有

NSDate *curDate = [NSDate date];

其值为上午9:13.我没有使用curDate的年、月和日部分.

我想要的是有9:15时间值的约会;如果我的时间值是9:16,我想把它提前到9:20,以此类推.

我怎样才能用NSDate做到这一点?

推荐答案

取分钟值,除以5四舍五入,得到下一个最高的5分钟单位,乘以5,以分钟为单位,然后构造一个新的NSDate.

NSDateComponents *time = [[NSCalendar currentCalendar]
                          components:NSHourCalendarUnit | NSMinuteCalendarUnit
                            fromDate:curDate];
NSInteger minutes = [time minute];
float minuteUnit = ceil((float) minutes / 5.0);
minutes = minuteUnit * 5.0;
[time setMinute: minutes];
curDate = [[NSCalendar currentCalendar] dateFromComponents:time];

Objective-c相关问答推荐

使用 ARC,什么更好:alloc 或 autorelease 初始化程序?

从日、月、年生成 NSDate

是否可以在 nsstring 中包含引号?

以原子方式写入文件与不写入文件之间的区别

iOS 7 - viewDidLoad 和 viewDidAppear 之间的区别

当单元格全屏时,为什么 UICollectionView 会记录错误?

UILabel 的角半径属性在 iOS 7.1 中不起作用

进入编辑模式时动画自定义绘制的 UITableViewCell

iPhone - 什么是重用标识符(UITableViewCell)?

Electron邮件镇静 iOS 8

如何以编程方式移动 UIScrollView 以集中在键盘上方的控件中?

Objective-C:前向类声明

Objective C 中的调用方法或发送消息

如何在 Objective C 中将浮点数转换为 int?

UICollectionView 仅在用户双击时调用 didSelectItemAtIndexPath,当用户单击时不会调用

单例释放方法产生警告?

使用 respondsToSelector 时 suppress '...' is deprecated

通过情节提要加载时如何初始化视图?

CMTime 秒输出

如何使用图像和标签制作自定义 UIBarButtonItem?