我通常对此非常好,但我遇到了NSDate
对象的问题。我需要一个NSDate
明天早上8点(相对)。我将如何做到这一点,什么是最简单的方法?如何在上午8点为明天创建日期对象
2
A
回答
14
下面是如何WWDC 2011 session 117 - Performing Calendar Calculations教导我:
NSDate* now = [NSDate date] ;
NSDateComponents* tomorrowComponents = [NSDateComponents new] ;
tomorrowComponents.day = 1 ;
NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDate* tomorrow = [calendar dateByAddingComponents:tomorrowComponents toDate:now options:0] ;
NSDateComponents* tomorrowAt8AMComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow] ;
tomorrowAt8AMComponents.hour = 8 ;
NSDate* tomorrowAt8AM = [calendar dateFromComponents:tomorrowAt8AMComponents] ;
太糟糕了iOS不具备[NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]
。谢谢,rmaddy,指出了。
1
在雨燕2.1:
let now = NSDate()
let tomorrowComponents = NSDateComponents()
tomorrowComponents.day = 1
let calendar = NSCalendar.currentCalendar()
if let tomorrow = calendar.dateByAddingComponents(tomorrowComponents, toDate: now, options: NSCalendarOptions.MatchFirst) {
let flags: NSCalendarUnit = [.Era, .Year, .Month, .Day]
let tomorrowValidTime: NSDateComponents = calendar.components(flags, fromDate: tomorrow)
tomorrowValidTime.hour = 7
if let tomorrowMorning = calendar.dateFromComponents(tomorrowValidTime) {
return tomorrowMorning
}
}
0
斯威夫特3+
private func tomorrowMorning() -> Date? {
let now = Date()
var tomorrowComponents = DateComponents()
tomorrowComponents.day = 1
let calendar = Calendar.current
if let tomorrow = calendar.date(byAdding: tomorrowComponents, to: now) {
let components: Set<Calendar.Component> = [.era, .year, .month, .day]
var tomorrowValidTime = calendar.dateComponents(components, from: tomorrow)
tomorrowValidTime.hour = 7
if let tomorrowMorning = calendar.date(from: tomorrowValidTime) {
return tomorrowMorning
}
}
return nil
}
相关问题
- 1. Javascript:将一个新日期设置为明天上午8点
- 2. 如何在Python中获取今天下午5点的日期时间对象?
- 3. 如何在JAVA日历值中设置为8点钟的明天日期
- 4. php 8天创建的日期
- 5. 如何在android上每天每小时给予背景通知(例如上午7点到上午8点,上午9点,上午9点00分)
- 6. 转换特定日期(如“今天上午10点),以time_t的
- 7. 日期逻辑谜题:在上午8点
- 8. 检查日期时间后的今天上午8点服务器
- 9. 如何获得第二天上午8点的秒数?
- 10. 如何从URL创建日期对象?
- 11. 为什么在Google表单中的日期验证在上午8:00之前拒绝今天的日期?
- 12. 获取前一天午夜的日期时间对象
- 13. 创建日期对象
- 14. Timepicker:创建日期对象
- 15. 如何计算今天上午00:00:00的日期?
- 16. 水晶报表 - 公式显示日期早上6点 - 上午6点(上午12点 - 上午12点)
- 17. 如何在Python中创建一个日期对象,表示一组天数
- 18. 将日期对象分为天
- 19. PDO条件:今天创建日期为
- 20. 在春天创建对象
- 21. 输出日期到上午/下午
- 22. javascript日期添加上午下午
- 23. 查询从当天上午6点到第二天上午6点
- 24. Htaccess在某个日期上午12点到下午6点重定向
- 25. 根据时间上午6点到上午6点设置交易日期
- 26. 获取日期减去1的一天,但在exacty上午04点
- 27. Fullcalendar:开始一天早上8点,而不是午夜
- 28. 如何获取日期的小时,分钟和上午/下午?
- 29. 春天JSON日期为Java日期对象
- 30. 在PHP 5.2.17中创建空日期对象的日期时间
基于标签,这个问题似乎是为iOS。 'dateWithNaturalLanguageString:'方法仅适用于OSX,不适用于iOS。 – rmaddy 2013-03-07 03:02:53
好吧,现在它增加了8个小时我认为,但在上午8点,它不会增加一天,它会回到今天。虽然在明天只有一个是明天...这是我的控制台日志的所有三个日期http://cl.ly/NPH5 – 2013-03-07 05:09:09
而不是记录NSDate,你可以[使用NSDateFormatter来创建一个NSString]( http://i.stack.imgur.com/EXWgO.png)并记录下来? – 2013-03-07 12:19:34