如何在Swift中更改当天的小时和分钟?

时间:2016-03-17 23:49:32

标签: swift nsdate

如果我创建Date()来获取当前日期和时间,我想从中创建一个新日期但是有不同的小时,分​​钟和零秒,这是最简单的方法它使用Swift?我已经找到了很多这样的例子来获得'但不是设置'。

3 个答案:

答案 0 :(得分:67)

请注意,对于使用夏令时的区域设置,时钟更改日可能不会存在几个小时,或者可能会出现两次。以下两个解决方案都返回Date?并使用强制解包。您应该在应用中处理可能的nil

Swift 3,4和iOS 8 / OS X 10.9或更高版本

let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!

Swift 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)!

请注意,如果您致电print(date),则打印时间为UTC。这是在同一时刻,只是在与你不同的时区表达。使用NSDateFormatter将其转换为您当地的时间。

答案 1 :(得分:23)

swift 3日期延长时区

extension Date {
    public func setTime(hour: Int, min: Int, sec: Int, timeZoneAbbrev: String = "UTC") -> Date? {
        let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
        let cal = Calendar.current
        var components = cal.dateComponents(x, from: self)

        components.timeZone = TimeZone(abbreviation: timeZoneAbbrev)
        components.hour = hour
        components.minute = min
        components.second = sec

        return cal.date(from: components)
    }
}

答案 2 :(得分:1)

//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