如何使用Swift获得一天中的小时? [英] How to get the hour of the day with Swift?
本文介绍了如何使用Swift获得一天中的小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何在Swift中获得一天中的时间.
我已经尝试过NSCalendar
和NSDateComponents
,但是恐怕我只是从Swift开始.
How would I get the hour of the day in Swift.
I have tried NSCalendar
and NSDateComponents
, but I'm afraid I'm just starting with Swift.
推荐答案
Swift 5.0/4.0/3.0
let hour = Calendar.current.component(.hour, from: Date())
或者,如果您对12 hour AM/PM
日期格式感兴趣,请使用 NSDateFormatter
Or, if you're interested in 12 hour AM/PM
date format, then use NSDateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "hh a" // "a" prints "pm" or "am"
let hourString = formatter.string(from: Date()) // "12 AM"
如果需要分钟,秒和其他时间,请执行以下操作
If you want minutes, seconds and others, do as following
let date = Date() // save date, so all components use the same date
let calendar = Calendar.current // or e.g. Calendar(identifier: .persian)
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
在 Apple文档中查看可用的组件:
Check out available components on Apple docs:
.era, .year, .month, .day, .hour, .minute, .second,
.weekday, .weekdayOrdinal, .quarter, weekOfMonth, .weekOfYear,
.yearForWeekOfYear, .nanosecond, .calendar, .timezone
Swift 2.0
let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
Swift 1.0
let hour = NSCalendar.currentCalendar().component(.CalendarUnitHour, fromDate: NSDate())
这篇关于如何使用Swift获得一天中的小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文