let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!
雨燕2 使用NSDateComponents/DateComponents:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)
// Change the time to 9:30:00 in your locale
components.hour = 9
components.minute = 30
components.second = 0
let date = gregorian.dateFromComponents(components)!
//Increase the day & hours in Swift
let dateformat = DateFormatter()
let timeformat = DateFormatter()
dateformat.dateStyle = .medium
timeformat.timeStyle = .medium
//Increase Day
let currentdate = Date()
let currentdateshow = dateformat.string(from: currentdate)
textfield2.text = currentdateshow
let myCurrentdate = dateformat.date(from: dateTimeString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myCurrentdate) // Increase 1 Day
let tomorrowday = dateformat.string(from: tomorrow!)
text3.text = tomorrowday
text3.isEnabled = false
//increase Time
let time = Date()
let currenttime = timeformat.string(from: time)
text4.text = currenttime
let mycurrenttime = timeformat.date(from: currenttime)!
let increasetime = Calendar.current.date(byAdding: .hour, value: 2, to: mycurrenttime) //increase 2 hrs.
let increasemytime = timeformat.string(from: increasetime!)
text5.text = increasemytime
3条答案
按热度按时间4ioopgfo1#
请注意,对于使用夏令时的区域设置,在时钟更改日,某些小时可能不存在或可能出现两次。以下两种解决方案都返回
Date?
并使用强制展开。您应在应用中处理可能的nil
。Swift 3+和iOS 8 / OS X 10.9或更高版本
雨燕2
使用
NSDateComponents
/DateComponents
:注意,如果你调用
print(date)
,打印出来的时间是UTC。这是同一个时间点,只是用不同的时区表示。使用NSDateFormatter
将它转换成你的本地时间。slwdgvem2#
带时区的swift 3日期扩展
muk1a3rh3#