从 [NSDate date] 获取当前日期,但将时间设置为上午 10:00 [英] get current date from [NSDate date] but set the time to 10:00 am

查看:26
本文介绍了从 [NSDate date] 获取当前日期,但将时间设置为上午 10:00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重置从 [NSDate date] 检索到的当前日期,然后将时间更改为早上 10:00.

How can I reset the current date retrieved from [NSDate date] but then change the time to 10:00 in the morning.

推荐答案

与所有日期操作一样,您必须使用 NSDateComponentsNSCalendar

As with all date manipulation you have to use NSDateComponents and NSCalendar

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:10];
NSDate *today10am = [calendar dateFromComponents:components];

在 iOS8 中,Apple 引入了一种节省几行代码的便捷方法:

in iOS8 Apple introduced a convenience method that saves a few lines of code:

NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];

斯威夫特:

let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()

let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!

这篇关于从 [NSDate date] 获取当前日期,但将时间设置为上午 10:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆