3

我想在没有秒或毫秒的情况下将日期/时间保存在 CoreData 存储中。(我正在做一些处理以缩短时间,并且杂散的秒/毫秒变成了活动扳手。)降低秒数很容易:

NSDate *now = [NSDate date];
NSDateComponents *time = [[NSCalendar currentCalendar]
                          components:NSHourCalendarUnit | NSMinuteCalendarUnit 
                          | NSSecondCalendarUnit fromDate:now];
    NSDate *nowMinus = [now addTimeInterval:-time.second];
    // e.g. 29 Aug 10 4:43:05 -> 29 Aug 10 4:43:00

这可以很好地将秒数归零,但是我找不到可以用来将毫秒数归零的 NSMillisecondCalendarUnit,我需要这样做。有任何想法吗?谢谢。

4

1 回答 1

8

timeIntervalSince1970返回自 1970 年 1 月 1 日以来的秒数(以双精度形式)。您可以使用此时间截断您喜欢的任何秒数。要向下舍入到最接近的分钟,您可以执行以下操作:

NSTimeInterval timeSince1970 = [[NSDate date] timeIntervalSince1970];

timeSince1970 -= fmod(timeSince1970, 60); // subtract away any extra seconds

NSDate *nowMinus = [NSDate dateWithTimeIntervalSince1970:timeSince1970];

浮点数据类型本质上是不精确的,但上面的数据可能足够精确以满足您的需求。

于 2010-08-29T21:08:17.247 回答