从操场开始。我正在尝试创建一个简单的应用程序。

我创建了一个date对象,就像这样:

var date = NSDate()

我怎样才能得到当前的时间?在其他语言中,我可以这样做:

var hour = date.hour

但我找不到任何这样的属性/方法。我找到了一个方法,dateWithCalendarFormat。我应该用这个吗?如果是,怎么做?


当前回答

扩展noiiv的史诗般的简洁解决方案,这里是更简洁的Swift 3/4实现:

斯威夫特3/4

let components = Calendar.current.dateComponents([.hour, .minute], from: Date())
let (hour, minute) = (components.hour, components.minute)

同时,扩展Leo Dabus的扩展,我们可以有:

extension Date {

    func components(_ components: Set<Calendar.Component>) -> DateComponents {
        return Calendar.current.dateComponents(components, from: self)
    }

    func component(_ component: Calendar.Component) -> Int {
        return Calendar.current.component(component, from: self)
    }

    var era: Int { return component(.era) }
    var year: Int { return component(.year) }
    var month: Int { return component(.month) }
    var day: Int { return component(.day) }
    var hour: Int { return component(.hour) }
    var minute: Int { return component(.minute) }
    var second: Int { return component(.second) }
    var weekday: Int { return component(.weekday) }
    var weekdayOrdinal: Int { return component(.weekdayOrdinal) }
    var quarter: Int { return component(.quarter) }
    var weekOfMonth: Int { return component(.weekOfMonth) }
    var weekOfYear: Int { return component(.weekOfYear) }
    var yearForWeekOfYear: Int { return component(.yearForWeekOfYear) }
    var nanosecond: Int { return component(.nanosecond) }
    var calendar: Calendar? { return components([.calendar]).calendar }
    var timeZone: TimeZone? { return components([.timeZone]).timeZone }

}

像这样使用它:

let date = Date()
let (hour, minute) = (date.hour, date.minute)

其他回答

斯威夫特4:

extension Date
{
    func hour() -> Int
    {
    //Get Hour
    let calendar = Calendar.current
    let components = calendar.component(.hour, from: self)
    let hour = components

    //Return Hour
    return hour
    }


    func minute() -> Int
    {
    //Get Minute
    let calendar = Calendar.current
    let components = calendar.component(.minute, from: self)
    let minute = components

    //Return Minute
    return minute
        }
}

Swift让创建和使用扩展变得非常容易。我创建了一个sharedCode.swift文件,并在其中放入枚举、扩展名和其他有趣的东西。我创建了一个NSDate扩展来添加一些典型的功能,这是费力和丑陋的输入一遍又一遍:

extension NSDate
{
    func hour() -> Int
    {
        //Get Hour
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hour = components.hour

        //Return Hour
        return hour
    }


    func minute() -> Int
    {
        //Get Minute
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minute = components.minute

        //Return Minute
        return minute
    }

    func toShortTimeString() -> String
    {
        //Get Short Time String
        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        let timeString = formatter.stringFromDate(self)

        //Return Short Time String
        return timeString
    }
}

使用这个扩展,你现在可以做一些事情,如:

        //Get Current Date
        let currentDate = NSDate()

        //Test Extensions in Log
        NSLog("(Current Hour = \(currentDate.hour())) (Current Minute = \(currentDate.minute())) (Current Short Time String = \(currentDate.toShortTimeString()))")

在上午11:51会写出来:

(当前小时= 11)(当前分钟= 51)(当前短时间字符串= 11:51 AM)

你可以使用Swift4或swif5如下所示:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let current_date = dateFormatter.string(from: date)
print("current_date-->",current_date)

输出:

2020-03-02

扩展noiiv的史诗般的简洁解决方案,这里是更简洁的Swift 3/4实现:

斯威夫特3/4

let components = Calendar.current.dateComponents([.hour, .minute], from: Date())
let (hour, minute) = (components.hour, components.minute)

同时,扩展Leo Dabus的扩展,我们可以有:

extension Date {

    func components(_ components: Set<Calendar.Component>) -> DateComponents {
        return Calendar.current.dateComponents(components, from: self)
    }

    func component(_ component: Calendar.Component) -> Int {
        return Calendar.current.component(component, from: self)
    }

    var era: Int { return component(.era) }
    var year: Int { return component(.year) }
    var month: Int { return component(.month) }
    var day: Int { return component(.day) }
    var hour: Int { return component(.hour) }
    var minute: Int { return component(.minute) }
    var second: Int { return component(.second) }
    var weekday: Int { return component(.weekday) }
    var weekdayOrdinal: Int { return component(.weekdayOrdinal) }
    var quarter: Int { return component(.quarter) }
    var weekOfMonth: Int { return component(.weekOfMonth) }
    var weekOfYear: Int { return component(.weekOfYear) }
    var yearForWeekOfYear: Int { return component(.yearForWeekOfYear) }
    var nanosecond: Int { return component(.nanosecond) }
    var calendar: Calendar? { return components([.calendar]).calendar }
    var timeZone: TimeZone? { return components([.timeZone]).timeZone }

}

像这样使用它:

let date = Date()
let (hour, minute) = (date.hour, date.minute)

在Swift 5中,Foundation提供了许多从Date对象中获取小时值的方法。根据您的需要,您可以选择以下四个Playground代码片段之一。


# 1。使用Calendar dateComponents(_:from:)方法

Calendar有一个叫做dateComponents(_:from:)的方法。dateComponents(_:from:)有如下声明:

func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents

使用日历时区返回日期的所有日期组件。

用法:

import Foundation

let date = Date()
let dateComponents = Calendar.current.dateComponents([.hour], from: date)
let hour = dateComponents.hour
print(String(describing: hour)) // may print: Optional(13)

# 2。使用Calendar组件(_:from:)方法

Calendar有一个叫做component(_:from:)的方法。组件(_:from:)有以下声明:

返回日期的一个组件的值。

func component(_ component: Calendar.Component, from date: Date) -> Int

用法:

import Foundation

let date = Date()
let hour = Calendar.current.component(.hour, from: date)
print(hour) // may print: 13

# 3。使用DateFormatter dateFormat属性

DateFormatter有一个名为dateFormat的属性。dateFormat有如下声明:

var dateFormat: String! { get set }

接收方使用的日期格式字符串。

用法:

import Foundation

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH"
let hour = dateFormatter.string(from: date)
print(hour) // may print: 13

# 4。使用数据格式化器setLocalizedDateFormatFromTemplate(_:)方法

Dateformatter有一个名为setLocalizedDateFormatFromTemplate(_:)的方法。setLocalizedDateFormatFromTemplate(_:)有如下声明:

func setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String)

使用指定区域设置接收方的模板的日期格式。

用法:

import Foundation

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("HH")
let hour = dateFormatter.string(from: date)
print(hour) // may print: 13