NSDate零秒,没有四舍五入

时间:2011-03-16 18:27:56

标签: objective-c ios4 nsdate

我想知道是否有人可以用我的方法帮助我。我有以下方法,它会将NSDate对象的秒值清零:

- (NSDate *)dateWithZeroSeconds:(NSDate *)date {
    NSTimeInterval time = round([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
    return  [NSDate dateWithTimeIntervalSinceReferenceDate:time];
}

问题在于传递日期,例如:

2011-03-16 18:21:43 +0000

它返回:

2011-03-16 18:22:00 +0000

我不希望这种舍入发生,因为它是实际指定日期的用户,所以它需要精确到他们请求的那一分钟。

非常感谢任何帮助。

6 个答案:

答案 0 :(得分:29)

使用地板而不是圆形:

- (NSDate *)dateWithZeroSeconds:(NSDate *)date
{
    NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
    return  [NSDate dateWithTimeIntervalSinceReferenceDate:time];
}

答案 1 :(得分:24)

使用NSCalendar和NSDateComponents获取日期的各个部分。将seconds组件设置为0,然后从该NSDateComponents创建一个新日期。

答案 2 :(得分:5)

要完成,这里是使用NSCalendar和NSDateComponents引用iOS SDK 8.1的代码。

+ (NSDate *)truncateSecondsForDate:(NSDate *)fromDate;
{
     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
     NSCalendarUnit unitFlags = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
     NSDateComponents *fromDateComponents = [gregorian components:unitFlags fromDate:fromDate ];
     return [gregorian dateFromComponents:fromDateComponents];
}

请注意,从iOS 8开始,日历单元名称已更改。

答案 3 :(得分:2)

Swift 2.2版@Neil回答:

func truncateSecondsForDate(fromDate: NSDate) -> NSDate {

    let calendar : NSCalendar = NSCalendar.currentCalendar()
    let unitFlags : NSCalendarUnit = [.Era , .Year , .Month , .Day , .Hour , .Minute]
    let fromDateComponents: NSDateComponents = calendar.components(unitFlags, fromDate: fromDate)

    return calendar.dateFromComponents(fromDateComponents)!

}

答案 4 :(得分:2)

您可以使用rangeOfUnit:startDate:interval:forDate:

获取任何时间单位的开头 - 例如一分钟
NSDate *startOfMinuteDate;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMinute
                                startDate:&startOfMinuteDate 
                                 interval:NULL 
                                  forDate:originalDate];

答案 5 :(得分:0)

Swift 4版本:

func truncateSecondsForDate(fromDate: Date) -> Date {

    let calendar = Calendar.current
    let fromDateComponents: DateComponents = calendar.dateComponents([.era , .year , .month , .day , .hour , .minute], from: fromDate as Date) as DateComponents

    return calendar.date(from: fromDateComponents as DateComponents)! as Date
}