Time in Swift Swift offers extensive support for times and durations; here are some examples.
import Foundation
// We'll start by getting the current time.
let now = Date ()
print ( now )
// You can build a Date struct by providing the
// year, month, day, etc. Times are always associated
// with a TimeZone.
let then = DateComponents ( calendar : Calendar . current ,
timeZone : TimeZone ( abbreviation : "UTC" ),
year : 2009 ,
month : 11 ,
day : 17 ,
hour : 20 ,
minute : 34 ,
second : 58 ,
nanosecond : 651387237 ). date !
print ( then )
// You can extract the various components of the date
// value as expected.
let calendar = Calendar . current
print ( calendar . component (. year , from : then ))
print ( calendar . component (. month , from : then ))
print ( calendar . component (. day , from : then ))
print ( calendar . component (. hour , from : then ))
print ( calendar . component (. minute , from : then ))
print ( calendar . component (. second , from : then ))
print ( calendar . component (. nanosecond , from : then ))
print ( then . timeZone )
// The Monday-Sunday Weekday is also available.
print ( calendar . component (. weekday , from : then ))
// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
print ( then < now )
print ( then > now )
print ( then == now )
// The timeIntervalSince method returns a TimeInterval representing
// the interval between two times.
let diff = now . timeIntervalSince ( then )
print ( diff )
// We can compute the length of the duration in
// various units.
print ( diff / 3600 ) // Hours
print ( diff / 60 ) // Minutes
print ( diff ) // Seconds
print ( diff * 1_000_000_000 ) // Nanoseconds
// You can use addingTimeInterval to advance a time by a given
// duration, or with a negative value to move backwards by a
// duration.
print ( then . addingTimeInterval ( diff ))
print ( then . addingTimeInterval ( - diff ))
To run the program, save it as TimeExample.swift
and use swift
command:
$ swift TimeExample.swift
2023-06-07 12:34:56 +0000
2009-11-17 20:34:58 +0000
2009
11
17
20
34
58
651387237
GMT ( fixed)
3
true
false
false
427112098.12345678
118642.24948151855
7118534.969690979
427112098.12345678
427112098123456780
2023-06-07 12:34:56 +0000
1996-05-01 04:35:00 +0000
This Swift code demonstrates various operations with dates and times, including creating dates, extracting components, comparing dates, calculating time intervals, and performing arithmetic with dates. The Date
struct in Swift is used to represent a point in time, similar to the time.Time
type in Go. The Calendar
class is used for more complex date and time calculations.
Next, we’ll look at the related idea of time relative to the Unix epoch.