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

pxyaymoc  于 2022-12-22  发布在  Swift
关注(0)|答案(3)|浏览(133)

如果我创建一个Date()来获取当前的日期和时间,我想创建一个新的日期,但是使用不同的小时,分钟和零秒,使用Swift最简单的方法是什么?我已经找到了很多使用“获取”而不是“设置”的例子。

4ioopgfo

4ioopgfo1#

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

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

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

注意,如果你调用print(date),打印出来的时间是UTC。这是同一个时间点,只是用不同的时区表示。使用NSDateFormatter将它转换成你的本地时间。

slwdgvem

slwdgvem2#

带时区的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)
    }
}
muk1a3rh

muk1a3rh3#

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

相关问题