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 (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
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
 
doc
docdoc
doc
PlanetExpressATX
 
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 Date
Shuo 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
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
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
 
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
 
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
 
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 Date
Shuo Chen
 
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
 
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
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 

More from allanh0526 (18)

Webp
WebpWebp
Webp
allanh0526
 
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
 
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
 
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
 

Recently uploaded (20)

Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 

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中关于日期类的使用指引