Variables of type Date
handle date and time for us, which can be a complex topic due to the various formats, languages, and time zones used around the world.
Creating Date with the current time
The first step in working with dates and times is to create a Date
object. This object has several initializers, the first one we'll see is the parameterless initializer, which returns the current date and time.
let now = Date()
print(now) // The console shows: 2021-01-22 19:12:28 +0000
import SwiftUI
or import Foundation
in order to use Date objects.
The Timestamp concept
A Timestamp
is simply the number of seconds that have passed since January 1, 1970, at 00:00 UTC. This is an international convention and is useful for working with dates because this number is independent of formats, languages, or time zones.
For example, we can initialize a Date
object with the Timestamp parameter.
let date = Date(timeIntervalSince1970: 72)
print(date) // The console shows: 1970-01-01 00:01:12 +0000
As you can see, it shows the date 1 minute and 12 seconds after January 1, 1970, at 00:00. The current Timestamp is approximately 1734966571.
Date formatter
To display dates and times in different formats, we can use the DateFormatter
object. Let's see how it works.
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
print(dateFormatter.string(from: date)) // The console shows: Jan 22, 2021 at 8:20 PM
With DateFormatter
, we can format both the date (dateStyle
) and the time (timeStyle
). Using the string(from:)
method, we can display the date and time as a String
. The format of this String
depends on the device's settings, so we don't need to worry about translating anything.
Converting a String to Date
Sometimes, we got dates in String
format. This isn't a problem if they always follow the same format, even in different languages, because we can convert them to a Date
, and DateFormatter
will display the date according to the device's settings.
To do this we'll use DateFormatter
. First, we define the format we need to convert, and then we use the date(from:)
method. The result is an Optional
because there's a chance the conversion could fail if the format is incorrect or if it's not a valid date. Once we have our Date
object, we can use it as shown below.
let dateString = "2021-01-22 19:29:47"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: dateString) {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
print(dateFormatter.string(from: date)) // The console shows: Jan 22, 2021
}
Be the first to comment