本文介绍了截断NSDate(零时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用时间 0小时, 0分钟和 0秒生成一个新的NSDate
.源日期可以是任意随机的NSDate
.
I want to generate a new NSDate
with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random NSDate
.
有没有办法做到这一点?该文档对此没有帮助.
Is there a way to achieve this? The documentation did not help me with this.
示例
拥有:2010-10-30 10:14:13 GMT
想要:2010-10-30 00:00:00 GMT
推荐答案
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
date
是您要从中删除时间的日期.
date
is the date you want to remove the time from.
这会分隔日期和时间,并使用默认时间(00:00:00)创建一个新日期.
This separates the date and time and creates a new date with the default time (00:00:00).
编辑
要考虑时区:
NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
这篇关于截断NSDate(零时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!