SlideShare a Scribd company logo
How to work with dates and
times in Swift 3
Allan Shih
Agenda
● Date and Time programming in Swift 3
● Date and Time classes
○ Date
○ DateComponents
○ DateFormatter
○ Calendar
○ Locale
○ TimeZone
● Reference
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
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
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
Date and time classes
Swift’s Date struct
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
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())
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
Swift’s Calendar and DateComponents
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
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.
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.
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.
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
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
Swift’s DateFormatter
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
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
DateStyles
let testDate = Date(timeIntervalSince1970: 1493899996) // 2017-05-04 12:13:16
let myFormatter = DateFormatter()
myFormatter.dateStyle = .short
print(“short date: (myFormatter.string(from: testDate))”) // "5/4/17"
myFormatter.dateStyle = .medium
print(myFormatter.string(from: testDate)) // "Mar 4, 2017"
myFormatter.dateStyle = .long
print(myFormatter.string(from: testDate)) // "Mar 4, 2017"
myFormatter.dateStyle = .full
print(myFormatter.string(from: testDate)) // "Thursday, May 4, 2017"
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
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
Custom date/time formats
myFormatter.dateFormat = "’Year:’ y ‘Month:’ M ‘Day:’ d"
myFormatter.string(from: testDate) // "Year: 2017 Month: 5 Day: 4"
myFormatter.dateFormat = "MM/dd/yy"
myFormatter.string(from: testDate) // "05/04/17"
myFormatter.dateFormat = "MMM dd, yyyy"
myFormatter.string(from: testDate) // "May 04, 2017"
myFormatter.dateFormat = "E MMM dd, yyyy"
myFormatter.string(from: testDate) // "Thu May 04, 2017"
myFormatter.dateFormat = "EEEE, MMMM dd, yyyy' at 'h:mm a."
myFormatter.string(from: testDate) // "Thursday, May 04, 2017 at 8:13 PM."
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
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
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
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
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
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
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)
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)
Reference
● API Reference - Dateformatter
● How to work with dates and times in Swift 3
● USING DATE, TIMEINTERVAL, AND DATECOMPONENTS IN SWIFT 3
● Swift3.0中关于日期类的使用指引

More Related Content

Similar to How to work with dates and times in swift 3

Date object.pptx date and object v
Date object.pptx date and object        vDate object.pptx date and object        v
Date object.pptx date and object v
22x026
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
VISHNUSHANKARSINGH3
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
Ganesh Samarthyam
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
PlanetExpressATX
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
Computer programming 2 Lesson 14
Computer programming 2  Lesson 14Computer programming 2  Lesson 14
Computer programming 2 Lesson 14
MLG College of Learning, Inc
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
Kenji HASUNUMA
 
Datetime - Julian Date
Datetime - Julian DateDatetime - Julian Date
Datetime - Julian DateShuo Chen
 
Java 8 date & time api
Java 8 date & time apiJava 8 date & time api
Java 8 date & time api
Rasheed Waraich
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
Serhii Kartashov
 
ThreeTen
ThreeTenThreeTen
ThreeTen
彥彬 洪
 
Python time
Python timePython time
Python time
Janu Jahnavi
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
Kenji HASUNUMA
 
Generating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlGenerating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in Posgresql
Workhorse Computing
 
10. timestamp
10. timestamp10. timestamp
10. timestamp
Amrit Kaur
 

Similar to How to work with dates and times in swift 3 (20)

Date object.pptx date and object v
Date object.pptx date and object        vDate object.pptx date and object        v
Date object.pptx date and object v
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
 
doc
docdoc
doc
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
 
Computer programming 2 Lesson 14
Computer programming 2  Lesson 14Computer programming 2  Lesson 14
Computer programming 2 Lesson 14
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
Datetime - Julian Date
Datetime - Julian DateDatetime - Julian Date
Datetime - Julian Date
 
Java 8 date & time api
Java 8 date & time apiJava 8 date & time api
Java 8 date & time api
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
 
ThreeTen
ThreeTenThreeTen
ThreeTen
 
Python time
Python timePython time
Python time
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
Generating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlGenerating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in Posgresql
 
10. timestamp
10. timestamp10. timestamp
10. timestamp
 

More from allanh0526

Webp
WebpWebp
Digital authentication
Digital authenticationDigital authentication
Digital authentication
allanh0526
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkins
allanh0526
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slather
allanh0526
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
allanh0526
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcode
allanh0526
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
allanh0526
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
allanh0526
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swift
allanh0526
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swift
allanh0526
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
allanh0526
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
allanh0526
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
allanh0526
 
WebRTC
WebRTCWebRTC
WebRTC
allanh0526
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interface
allanh0526
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archiva
allanh0526
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclient
allanh0526
 

More from allanh0526 (18)

Webp
WebpWebp
Webp
 
Digital authentication
Digital authenticationDigital authentication
Digital authentication
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkins
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slather
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcode
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swift
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swift
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
 
WebRTC
WebRTCWebRTC
WebRTC
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interface
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archiva
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclient
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

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
  • 6. Date and time classes
  • 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
  • 11. Swift’s Calendar and DateComponents
  • 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
  • 21. DateStyles let testDate = Date(timeIntervalSince1970: 1493899996) // 2017-05-04 12:13:16 let myFormatter = DateFormatter() myFormatter.dateStyle = .short print(“short date: (myFormatter.string(from: testDate))”) // "5/4/17" myFormatter.dateStyle = .medium print(myFormatter.string(from: testDate)) // "Mar 4, 2017" myFormatter.dateStyle = .long print(myFormatter.string(from: testDate)) // "Mar 4, 2017" myFormatter.dateStyle = .full print(myFormatter.string(from: testDate)) // "Thursday, May 4, 2017"
  • 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
  • 24. Custom date/time formats myFormatter.dateFormat = "’Year:’ y ‘Month:’ M ‘Day:’ d" myFormatter.string(from: testDate) // "Year: 2017 Month: 5 Day: 4" myFormatter.dateFormat = "MM/dd/yy" myFormatter.string(from: testDate) // "05/04/17" myFormatter.dateFormat = "MMM dd, yyyy" myFormatter.string(from: testDate) // "May 04, 2017" myFormatter.dateFormat = "E MMM dd, yyyy" myFormatter.string(from: testDate) // "Thu May 04, 2017" myFormatter.dateFormat = "EEEE, MMMM dd, yyyy' at 'h:mm a." myFormatter.string(from: testDate) // "Thursday, May 04, 2017 at 8:13 PM."
  • 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中关于日期类的使用指引