我想在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,我需要这样做。有什么想法吗?谢谢。
发布于 2010-08-30 05:08:17
timeIntervalSince1970返回自1970年1月1日以来的秒数(以双精度表示)。您可以使用此时间截断您喜欢的任何秒数。要向下舍入到最接近的分钟,您可以这样做:
NSTimeInterval timeSince1970 = [[NSDate date] timeIntervalSince1970];
timeSince1970 -= fmod(timeSince1970, 60); // subtract away any extra seconds
NSDate *nowMinus = [NSDate dateWithTimeIntervalSince1970:timeSince1970];浮点数据类型本质上是不精确的,但上述数据类型可能足以满足您的需要。
https://stackoverflow.com/questions/3596460
复制相似问题