本文介绍了如何在 Swift 中更改当天的小时和分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个 Date() 来获取当前日期和时间,我想从中创建一个新的日期,但具有不同的小时、分钟和零秒,最简单的方法是什么用 Swift 做吗?我已经找到了很多带有获取"而不是设置"的示例.

If I create a Date() to get the current date and time, I want to create a new date from that but with different hour, minute, and zero seconds, what's the easiest way to do it using Swift? I've been finding so many examples with 'getting' but not 'setting'.

推荐答案

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

Be aware that for locales that uses Daylight Saving Times, some hours may not exist on the clock change days or they may occur twice. Both solutions below return a Date? and use force-unwrapping. You should handle possible nil in your app.

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 将其转换为您的本地时间.

Note that if you call print(date), the printed time is in UTC. It's the same moment in time, just expressed in a different timezone from yours. Use a NSDateFormatter to convert it to your local time.

这篇关于如何在 Swift 中更改当天的小时和分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:40