This document discusses working with dates and times in Swift 3. It covers the Date, DateComponents, DateFormatter, Calendar, Locale, and TimeZone classes. It shows how to create and format dates, extract date components, perform date calculations like adding/subtracting days/weeks, and compare dates. Key aspects covered include converting between dates and strings, building dates from components, and getting the difference between dates in seconds or days.
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
How to work with dates and times in swift 3
1. How to work with dates and
times in Swift 3
Allan Shih
2. Agenda
● Date and Time programming in Swift 3
● Date and Time classes
○ Date
○ DateComponents
○ DateFormatter
○ Calendar
○ Locale
○ TimeZone
● Reference
3. Date and time programming in Swift 3
● Break a date into its components and access each date
part separately (day, month, etc).
● Convert between dates and strings
● Compare dates
● Calculate dates in the future or in the past
● Calculate date differences
4. Date and time classes
● Date
○ Represents a single point in time
○ Expressed in seconds before or after midnight, jan 1, 2001 UTC
● DateComponents
○ Represents the parts of a given date
● DateFormatter
○ Convert dates into formatted strings
● String
○ The text representation of a date and time
5. Date and time classes
● Calendar
○ Provides a context for dates and the ability to do date arithmetic
● Locale
○ Represents a users’s regional settings, including those for date and
time.
● TimeZone
○ Convert dates into formatted strings
8. Create current Date
Create a Date representing the current date and time
Result
let now = Date()
let fiveMinutesAgo = Date(timeIntervalSinceNow: -5 * 60)
let fiveMinutesFromNow = Date(timeIntervalSinceNow: 5 * 60)
now: 2017-05-04 09:13:58 +0000
fiveMinutesAgo: 2017-05-04 09:08:58 +0000
fiveMinutesFromNow: 2017-05-04 09:18:58 +0000
9. Set a date based on the time interval
● TimeInterval is a measure of time using seconds. ( Double type )
● Get a date one minute from now.
● Get a date an hour from now
let minute: TimeInterval = 60.0
let hour: TimeInterval = 60.0 * minute
let day: TimeInterval = 24 * hour
let date = Date(timeIntervalSinceNow: minute)
let date = Date(timeInterval: hour, since: Date())
10. Unix time
Unix time defines time as a number of seconds after the Unix Epoch, January
1, 1970, 00:00:00 UTC.
Result
let oneYear = TimeInterval(60 * 60 * 24 * 365)
let newYears1971 = Date(timeIntervalSince1970: oneYear)
let newYears1969 = Date(timeIntervalSince1970: -oneYear)
newYears1971: 1971-01-01 00:00:00 +0000
newYears1969: 1969-01-01 00:00:00 +0000
12. Build Date using properties
Create an DateComponents struct, providing values for the year, month, and
day parameters, and nil for all the others.
Result
let userCalendar = Calendar.current
let dateComponents = DateComponents(year: 1876, month: 3, day: 10,
hour: nil, minute: nil, second: nil)
let testDate = userCalendar.date(from: dateComponents)
testDate: 1876-03-09 15:54:00 +0000
13. DateComponents property
Property Description
calendar The calendar system for the date represented by this set of DateComponents.
We got these DateComponents by converting a Date using a Gregorian
Calendar, so in this case, this value is gregorian.
day The day number of this particular date and time. For January 27, 2010, 10:00:00
UTC, this value is 27.
era The era for this particular date, which depends on the date’s calendar system. In
this case, we’re using the Gregorian calendar, which has two eras:
● BCE (before the Common Era), represented by the integer value 0
● CE (Common Era), represented by the integer value 1
hour The hour number of this particular date and time. For January 27, 2010, 10:00:00
UTC, this value is 18, because in my time zone, 10:00:00 UTC is 18:00:00.
minute The minute number of this particular date and time. For January 27, 2010,
10:00:00 UTC, this value is 0.
14. DateComponents property
Property Description
month The month number of this particular date and time. For January 27, 2010,
10:00:00 UTC, this value is 1.
nanosecond The nanosecond number of this particular date and time. For January 27, 2010,
10:00:00 UTC, this value is 0.
quarter The quarter number of this particular date and time. January 27, 2010, 10:00:00
UTC, is in the first quarter of the year, so this value is 0.
second The second number of this particular date and time. For January 27, 2010,
10:00:00 UTC, this value is 0.
timeZone The time zone of this particular date and time. I’m in the UTC+8 time zone, so
this value is set to that time zone.
weekday The day of the week of this particular date and time. In the Gregorian calendar,
Sunday is 1, Monday is 2, Tuesday is 3, and so on. January 27, 2010, was a
Wednesday, so this value is 4.
15. DateComponents property
Property Description
weekdayOrdinal The position of the weekday within the next larger specified calendar unit, which
in this case is a month. So this specifies nth weekday of the given month. Jauary
27, 2010 was on the 4th Wednesday of the month, so this value is 4.
weekOfMonth The week of the month of this particular date and time. January 27, 2010 fell on
the 5th week of January 2010, so this value is 5.
weekOfYear The week of the year of this particular date and time. January 27, 2010 fell on
the 5th week of 2010, so this value is 5.
year The year number of this particular date and time. For January 27, 2010, 10:00:00
UTC, this value is 2010.
yearForWeekOfYear The ISO 8601 week-numbering year of the receiver.
16. Build Date using properties
Create a blank DateComponents struct, and then setting its year, month, and
day properties.
Result
let userCalendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.year = 1973
dateComponents.month = 4
dateComponents.day = 3
let testDate = userCalendar.date(from: dateComponents)
testDate: 1973-04-03 15:54:00 +0000
17. Extract properties from Date
Extracts the year, month, day, hour, minute, what day of the week and week of
the year from a Date
let userCalendar = Calendar.current
let testDate = Date(timeIntervalSince1970: 1493899996)
let dateComponents = userCalendar.dateComponents(
[.year, .month, .day, .hour, .minute, .weekday, .weekOfYear], from: testDate)
dateComponents.year // 2017
dateComponents.month // 5
dateComponents.day // 4
dateComponents.hour // 12
dateComponents.minute // 13
dateComponents.weekday // 5
dateComponents.weekOfYear // 18
19. Convert a Date into a String
Using short date style to convert Date String.
Result
let testDate = Date(timeIntervalSince1970: 1493899996) // 2017-05-04 12:13:16
let myFormatter = DateFormatter()
myFormatter.dateStyle = .short
print(“short date: (myFormatter.string(from: testDate))”)
short date: 5/4/17
20. Convert a Date into a String
Using short time style to convert Date String.
Result
let testDate = Date(timeIntervalSince1970: 1493899996) // 2017-05-04 12:13:16
let myFormatter = DateFormatter()
myFormatter.timeStyle = .short
print(“short date: (myFormatter.string(from: testDate))”)
short date: 8:13 PM
22. DateStyles and TimeStyles
myFormatter.dateStyle = .short
myFormatter.timeStyle = .short
print(“short date: (myFormatter.string(from: testDate))”) // 5/4/17, 8:13 PM
myFormatter.dateStyle = .medium
myFormatter.timeStyle = .medium
print(myFormatter.string(from: testDate)) // May 4, 2017, 8:13:16 PM
myFormatter.dateStyle = .long
myFormatter.dateStyle = .long
print(myFormatter.string(from: testDate)) // May 4, 2017 at 8:13:16 PM GMT+8
myFormatter.dateStyle = .full
myFormatter.timeStyle = .full
// Thursday, May 4, 2017 at 8:13:16 PM Taipei Standard Time
23. Custom date/time formats
Using short date style to convert Date String.
Result
let testDate = Date(timeIntervalSince1970: 1493899996) // 2017-05-04 12:13:16
print("current locale: (Locale.current)")
let myFormatter = DateFormatter()
myFormatter.locale = Locale(identifier: "en_US_POSIX")
myFormatter.dateFormat = "y-MM-dd"
print(“short date: (myFormatter.string(from: testDate))”)
current locale: en_US (current)
short date: 2017-05-04
25. Convert a String into a Date
Use DateFormatter’s date(from:) method to convert a String into a Date.
Result
let myFormatter = DateFormatter()
myFormatter.locale = Locale(identifier: "en_US_POSIX")
myFormatter.dateFormat = "yyyy/MM/dd hh:mm Z"
let date1 = myFormatter.date(from: "2015/03/07 11:00 -0500")
let date2 = myFormatter.date(from: "Mar 7, 2015, 11:00:00 AM")
date1: Optional(2015-03-07 16:00:00 +0000)
date2: nil
26. Convert a String into a Date with dateStyle
Use DateFormatter’s date(from:) method to convert a String into a Date.
Result
let myFormatter = DateFormatter()
myFormatter.locale = Locale(identifier: "en_US_POSIX")
myFormatter.dateStyle = .short
let date1 = myFormatter.date(from: "5/4/17")
let date2 = myFormatter.date(from: "5/4/17 16:00:00")
let date3 = myFormatter.date(from: "2017-05-04")
date1: Optional(2017-05-04 00:00:00 +0000)
date2: Optional(2017-05-04 00:00:00 +0000)
date3: nil
27. Convert a String into a Date with dateStyle and timeStyle
Use DateFormatter’s date(from:) method to convert a String into a Date.
Result
let myFormatter = DateFormatter()
myFormatter.locale = Locale(identifier: "en_US_POSIX")
myFormatter.dateStyle = .medium
myFormatter.timeStyle = .medium
let date1 = myFormatter.date(from: "5/417")
let date2 = myFormatter.date(from: "May 4, 2017, 8:13:16 PM")
let date3 = myFormatter.date(from: "May 4, 2017")
date1: nil
date2: Optional(2017-05-04 20:13:16 +0000)
date3: nil
28. Date comparisons
Use familiar comparison operators — <, <=, ==, !=, >, >= to tell which Date
came first, or if they represent the same point in time.
Result
let now = Date()
let fiveMinutesAgo = Date(timeIntervalSinceNow: -5 * 60)
let fiveMinutesFromNow = Date(timeIntervalSinceNow: 5 * 60)
print(now > fiveMinutesAgo)
print(fiveMinutesFromNow < fiveMinutesAgo)
print(now == fiveMinutesFromNow)
true
false
false
29. Date comparisons in seconds
Get the difference between two dates and times in seconds
Result
let now = Date()
let fiveMinutesAgo = Date(timeIntervalSinceNow: -5 * 60)
let fiveMinutesFromNow = Date(timeIntervalSinceNow: 5 * 60)
print(now.timeIntervalSince(fiveMinutesAgo))
print(now.timeIntervalSince(fiveMinutesFromNow))
300.0
-300.0
30. Date comparisons in days
Get the difference between two dates and times in days
let userCalendar = Calendar.current
let now = Date()
let dateComponents = DateComponents(year: 1876, month: 3, day: 10,
hour: nil, minute: nil, second: nil)
let testDate = userCalendar.date(from: dateComponents)
let daysBetweenTest = userCalendar.dateComponents([.day],
from: testDate,
to: now)
print(daysBetweenTest.day ?? 0) // 51555
31. Date addition ( before or after 5 day)
Create a Date representing the current date and time
Use byAdding method of the Calendar
let now = Date()
let fiveDaysAgo = Date(timeIntervalSinceNow: -5 * 60 * 60 * 24)
let fiveDaysFromNow = Date(timeIntervalSinceNow: 5 * 60 * 60 * 24)
let userCalendar = Calendar.current
let now = Date()
let fiveDaysAgo = userCalendar.date(byAdding: .day, value: -5, to: now)
let fiveDaysFromNow = userCalendar.date(byAdding: .day, value: 5, to: now)
32. Date addition ( before or after 5 weeks)
Create a Date representing the current date and time
Use byAdding method of the Calendar
let now = Date()
let fiveWeeksAgo = Date(timeIntervalSinceNow: -5 * 60 * 60 * 24 * 7)
let fiveWeeksFromNow = Date(timeIntervalSinceNow: 5 * 60 * 60 * 24 * 7)
let userCalendar = Calendar.current
let now = Date()
let fiveWeeksAgo = userCalendar.date(byAdding: .weekOfYear, value: -5, to: now)
let fiveWeeksFromNow = userCalendar.date(byAdding: .weekOfYear, value: 5, to: now)
33. Reference
● API Reference - Dateformatter
● How to work with dates and times in Swift 3
● USING DATE, TIMEINTERVAL, AND DATECOMPONENTS IN SWIFT 3
● Swift3.0中关于日期类的使用指引