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
我不希望发生这种舍入,因为实际上是用户指定日期,因此需要精确到他们要求的分钟。
非常感谢任何帮助。
I would like to know if 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用地板代替圆形:
Use floor instead of round:
使用 NSCalendar 和 NSDateComponents 获取日期的各个部分。将秒组件设置为 0,然后从该 NSDateComponents 创建一个新日期。
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.
为了完整起见,这里是使用 NSCalendar 和 NSDateComponents 引用 iOS SDK 8.1 的代码。
请注意,从 iOS 8 开始,日历单位名称已更改。
To be complete, here is the code referenced to iOS SDK 8.1 using NSCalendar and NSDateComponents.
Note that as of iOS 8 the calendar unit names have changed.
您可以使用
rangeOfUnit:startDate:interval:forDate:
获取任何时间单位(例如一分钟)的开始时间You can get the start of any time unit — such as an minute — with
rangeOfUnit:startDate:interval:forDate:
Swift 2.2 版本的@Neil 回答:
Swift 2.2 version of @Neil answer:
斯威夫特 4 版本:
Swift 4 version :