我通常對此非常好,但我遇到了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