如何使用 NSDate 在 Swift 3 中获取时间(小时、分钟、秒)? [英] How to get time (hour, minute, second) in Swift 3 using NSDate?

查看:41
本文介绍了如何使用 NSDate 在 Swift 3 中获取时间(小时、分钟、秒)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Swift 3 中的 NSDate 类中确定小时、分钟和秒?

How can you determine the hour, minute and second from NSDate class in Swift 3?

在 Swift 2 中:

In Swift 2:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: date)
let hour = components.hour

斯威夫特 3?

推荐答案

Swift 3.0 中,Apple 移除了NS"前缀,让一切变得简单.以下是从日期"类(NSDate 替代)中获取小时、分钟和秒的方法

In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = (hour):(minutes):(seconds)")

像这样你可以通过相应的传递来获得时代,年,月,日期等.

Like these you can get era, year, month, date etc. by passing corresponding.

这篇关于如何使用 NSDate 在 Swift 3 中获取时间(小时、分钟、秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆