How to get the current time as datetime
Just started with the playground. I'm trying to create a simple app.
I've created a date object like this:
var date = NSDate()
How can I get the current hour? In other languages I can do something like this:
var hour = date.hour
But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat
. Should I use that? If so, HOW?
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
Tested with Swift 4
Getting the Current Date and Time
You can get the current date and time as simply as this:
let currentDateTime = Date()
However, Date
is a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. I can see that number for the current datetime by using
Date().timeIntervalSinceReferenceDate
At the time of this writing, it returned 497626515.185066
, probably not exactly what you are looking for. Keep reading.
Creating Another Date and Time
Method 1
If you know the number of seconds before or after the reference date, you can use that.
let someOtherDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM
Method 2
Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date
. For this you can use DateComponents
to specify the components and then Calendar
to create the date. The Calendar
gives the Date
context. Otherwise, how would it know what time zone or calendar to express it in?
// 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)
Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.
Method 3
The most succinct way (but not necessarily the best) could be to use DateFormatter
.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")
The Unicode technical standards show other formats that DateFormatter
supports.
Displaying the Date and Time
Method 1
If you want to just display certain components of the date or time you can use CalendarUnit
to specify the components that you want to extract from 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
See this answer also.
Method 2
Method 1 gave you the components, but it would be a lot of work to format those numbers for every style, language, and region. And you don't need to. This has already been done for you with the DateFormatter
class.
// 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
Here is a continuation of the above code that shows more formatting options:
// "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)
Keep in mind, though, that this is for English with the region set to the US. For other languages and regions the formatting will look different.
Further study
- How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents
- How to work with dates and times in Swift 3, part 2: DateFormatter
- How to work with dates and times in Swift 3, part 3: Date arithmetic
You could also use NSDateFormatter's convenience method, e.g.,
func printTimestamp() {
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
print(timestamp)
}
printTimestamp() // Prints "Sep 9, 2014, 4:30 AM"
Swift makes it really easy to create and use extensions. I create a sharedCode.swift
file and put enums, extensions, and other fun stuff in it. I created a NSDate
extension to add some typical functionality which is laborious and ugly to type over and over again:
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
}
}
using this extension you can now do something like:
//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()))")
Which for 11:51 AM would write out:
(Current Hour = 11) (Current Minute = 51) (Current Short Time String = 11:51 AM)
Swift 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
OUTPUT
2018-May-01 10:41:31