Answers:
Swift 3更新:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
我这样做:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
在Objective-c中看到相同的问题如何从NSDate获得小时和分钟?
与Nate的答案相比,您会得到一个带有数字的数字,而不是字符串……选择您的选择!
let components = calendar.components(.NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date)
,此处不再可以使用垂直斜杠。
let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date)
删除了多余的“。” 在NSCalendarUnit之前
let components = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
经过Swift 4测试
您可以像这样简单地获取当前日期和时间:
let currentDateTime = Date()
但是,Date
是一个64位浮点数,它测量自2001年1月1日UTC的引用日期以来的秒数。我可以使用看到当前日期时间的数字
Date().timeIntervalSinceReferenceDate
在撰写本文时,它返回了497626515.185066
,可能不完全是您想要的内容。继续阅读。
方法一
如果您知道参考日期之前或之后的秒数,则可以使用该秒数。
let someOtherDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM
方法2
当然,使用诸如年,月,日和小时(而不是相对秒)之类的方法来制作会更容易Date
。为此,您可以DateComponents
用来指定组件,然后Calendar
创建日期。在Calendar
给出了Date
上下文。否则,它将如何知道用哪个时区或日历表示?
// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34
// Create date from components
let userCalendar = Calendar.current // user calendar
let someDateTime = userCalendar.date(from: dateComponents)
其他时区缩写可以在此处找到。如果您将该字段留空,则默认值为使用用户的时区。
方法3
最简洁的方式(但不一定是最好的方式)可以使用DateFormatter
。
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")
在统一的技术标准表明其他格式是DateFormatter
支持的。
方法一
如果只想显示日期或时间的某些组成部分,则可以CalendarUnit
用来指定要从中提取的组成部分Date
。
// get the current date and time
let currentDateTime = Date()
// get the user's calendar
let userCalendar = Calendar.current
// choose which date and time components are needed
let requestedComponents: Set<Calendar.Component> = [
.year,
.month,
.day,
.hour,
.minute,
.second
]
// get the components
let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)
// now the components are available
dateTimeComponents.year // 2016
dateTimeComponents.month // 10
dateTimeComponents.day // 8
dateTimeComponents.hour // 22
dateTimeComponents.minute // 42
dateTimeComponents.second // 17
另请参阅此答案。
方法2
方法1为您提供了组件,但是要为每种样式,语言和地区设置这些数字格式将需要大量的工作。而且您不需要。本DateFormatter
课程已经为您完成。
// get the current date and time
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
这是上面代码的延续,显示了更多的格式选项:
// "10/8/16, 10:52 PM"
formatter.timeStyle = .short
formatter.dateStyle = .short
formatter.string(from: currentDateTime)
// "Oct 8, 2016, 10:52:30 PM"
formatter.timeStyle = .medium
formatter.dateStyle = .medium
formatter.string(from: currentDateTime)
// "October 8, 2016 at 10:52:30 PM GMT+8"
formatter.timeStyle = .long
formatter.dateStyle = .long
formatter.string(from: currentDateTime)
// "October 8, 2016"
formatter.timeStyle = .none
formatter.dateStyle = .long
formatter.string(from: currentDateTime)
// "10:52:30 PM"
formatter.timeStyle = .medium
formatter.dateStyle = .none
formatter.string(from: currentDateTime)
但是请记住,这是针对英语的,将区域设置为美国。对于其他语言和地区,格式看起来会有所不同。
您还可以使用NSDateFormatter的便捷方法,例如,
func printTimestamp() {
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
print(timestamp)
}
printTimestamp() // Prints "Sep 9, 2014, 4:30 AM"
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)
斯威夫特4
let dateFormatter : DateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970
输出值
2018年5月1日10:41:31
斯威夫特3:
static func currentTime() -> String {
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
return "\(hour):\(minutes)"
}
PS-不确定通过获取当前时间(和小时)作为日期时间来确切说明问题的含义,但希望以上内容能够解释足够多的答案。
使用Swift 5,Foundation
提供了许多方法来从Date
对象获取小时值。根据您的需要,您可以选择以下四个Playground代码片段之一。
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)
Calendar
component(_:from:)
方法Calendar
有一种称为的方法component(_:from:)
。component(_: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
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
Dateformatter
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
在Swift 3中
let date = Date()
let calendar = Calendar.current()
let hour = calendar.component(.hour, from: date)
let calendar = Calendar.current; let unitFlags: Set<Calendar.Component> = Set<Calendar.Component ([.hour]); let components = calendar.dateComponents(unitFlags, from: self)
//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)
//Time
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(DateAndTime.action), userInfo: nil, repeats: true)
}
func action()
{
//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)
//Time
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)
}
注意:计时器代码中的DateAndTime是类名称。
我知道有很多答案,但我认为对于许多人来说,我可能会更方便
extension String {
init(epoch: Double) {
let date = Date(timeIntervalSince1970: epoch)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ssZZZ"
self = dateFormatter.string(from: date)
}
}
你可以试试这个
func getTime() -> (hour:Int, min:Int, sec:Int) {
let currentDateTime = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour,.Minute,.Second], fromDate: currentDateTime)
let hour = components.hour
let min = components.minute
let sec = components.second
return (hour,min,sec)
}
现在调用该方法并接收带有小时,分钟和秒的日期
let currentTime = self.getTime()
print("Hour: \(currentTime.hour) Min: \(currentTime.min) Sec: \(currentTime.sec))")
您可以像波纹管一样快速使用4或5
let date = Date()
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = df.string(from: date)
Ouput会像波纹管一样
2019-12-20 09:40:08
Xcode 8.2.1•Swift 3.0.2
extension Date {
var hour: Int { return Calendar.autoupdatingCurrent.component(.hour, from: self) }
}
let date = Date() // "Mar 16, 2017, 3:43 PM"
let hour = date.hour // 15
Date().hour
扩展了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)
Date
对象获取年,月,日等信息时,无需返回可选参数。Btw Calendar组件方法更适合于单个组件
DateComponents.year
访问者是Int?
component
为那些访问者使用该方法
仅特定格式的日期
let dateFormatter1 = NSDateFormatter()
dateFormatter1.dateStyle = .MediumStyle
dateFormatter1.timeStyle = .NoStyle
dateFormatter1.dateFormat = "dd-MM-yyyy"
let date = dateFormatter1.stringFromDate(NSDate())
您可以像下面这样使用Swift4或Swift 5波纹管:
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
如果您需要以特定方式设置答案的格式,则可以轻松使用此方法,默认为“ dd-MM-yyyy”。
extension Date {
func today(format : String = "dd-MM-yyyy") -> String{
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: date)
}
}
获取今天的日期现在可以使用
Date().today() or Date().today("dd/MM/yyyy")
SWIFT 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
}
}
func getCurrentDate() -> Date {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateInString = dateFormatter.string(from: date)
let dateinDate = dateFormatter.date(from: dateInString)
return dateinDate!
}
这是SWIFT扩展名,用于获取您当前的设备定位时间(GMT)。
func getGMTTimeDate() -> Date {
var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
comp.calendar = Calendar.current
comp.timeZone = TimeZone(abbreviation: "GMT")!
return Calendar.current.date(from: comp)!
}
现在获取时间:-
Date().getGMTTimeDate()
可与Swift 5(Xcode 10和Xcode 11)配合使用(来自法国UTC)
func getCurrentDateTime() {
let now = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.dateFormat = "EEEE dd MMMM YYYY HH:mm"
myLabel.text = formatter.string(from: now)
myLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
myLabel.textColor = UIColor.black
}
如果只想显示日期,请设置 formatter.dateFormat
formatter.dateFormat = "EEEE dd MMMM YYYY"
要仅显示小时,请更改formatter.dateFormat
为
formatter.dateFormat = "HH:mm"
不要忘记添加getCurrentDateTime()
上viewDidLoad
。