开发者

NSDate zero out seconds without rounding up

I would like to know i开发者_Go百科f anyone can help me with my method. I have the following method, which will zero out the seconds value of a NSDate object:

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

The problem is when passed a date such as:

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

it returns:

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

I do not want this rounding to occur, as it is a user who is actually specifying the date, so it needs to be exact to the minute they request.

Any help is greatly appreciated.


Use floor instead of round:

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


Use NSCalendar and NSDateComponents to get the parts of the date. Set the seconds component to 0, then create a new date from that NSDateComponents.


To be complete, here is the code referenced to iOS SDK 8.1 using NSCalendar and NSDateComponents.

+ (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];
}

Note that as of iOS 8 the calendar unit names have changed.


You can get the start of any time unit — such as an minute — with rangeOfUnit:startDate:interval:forDate:

NSDate *startOfMinuteDate;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMinute
                                startDate:&startOfMinuteDate 
                                 interval:NULL 
                                  forDate:originalDate];


Swift 2.2 version of @Neil answer:

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)!

}


Swift 4 version :

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜