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)

PPTX
Date object.pptx date and object v
22x026
 
PDF
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
PPT
15. DateTime API.ppt
VISHNUSHANKARSINGH3
 
PDF
Java 8 Date and Time API
Ganesh Samarthyam
 
PDF
Introduction to Date and Time API 4
Kenji HASUNUMA
 
PDF
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
PDF
jkfdlsajfklafj
PlanetExpressATX
 
PDF
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
PPTX
Computer programming 2 Lesson 14
MLG College of Learning, Inc
 
PDF
Introduction to Date and Time API 3
Kenji HASUNUMA
 
PPTX
Datetime - Julian Date
Shuo Chen
 
PDF
Java 8 date & time api
Rasheed Waraich
 
PDF
Introduction to Date and Time API 4
Kenji HASUNUMA
 
PPTX
JSR 310. New Date API in Java 8
Serhii Kartashov
 
PDF
ThreeTen
彥彬 洪
 
PPTX
Python time
Janu Jahnavi
 
PDF
Introduction to Date and Time API 3
Kenji HASUNUMA
 
PDF
Generating & Querying Calendar Tables in Posgresql
Workhorse Computing
 
DOCX
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
Date object.pptx date and object v
22x026
 
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
15. DateTime API.ppt
VISHNUSHANKARSINGH3
 
Java 8 Date and Time API
Ganesh Samarthyam
 
Introduction to Date and Time API 4
Kenji HASUNUMA
 
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
jkfdlsajfklafj
PlanetExpressATX
 
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
Computer programming 2 Lesson 14
MLG College of Learning, Inc
 
Introduction to Date and Time API 3
Kenji HASUNUMA
 
Datetime - Julian Date
Shuo Chen
 
Java 8 date & time api
Rasheed Waraich
 
Introduction to Date and Time API 4
Kenji HASUNUMA
 
JSR 310. New Date API in Java 8
Serhii Kartashov
 
ThreeTen
彥彬 洪
 
Python time
Janu Jahnavi
 
Introduction to Date and Time API 3
Kenji HASUNUMA
 
Generating & Querying Calendar Tables in Posgresql
Workhorse Computing
 
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 

More from allanh0526 (18)

PPTX
Webp
allanh0526
 
PPTX
Digital authentication
allanh0526
 
PDF
Integration of slather and jenkins
allanh0526
 
PDF
How to generate code coverage reports in xcode with slather
allanh0526
 
PDF
Unit testing in xcode 8 with swift
allanh0526
 
PDF
Ui testing in xcode
allanh0526
 
PDF
Using a model view-view model architecture for iOS apps
allanh0526
 
PDF
iOS architecture patterns
allanh0526
 
PDF
ThingMaker in Swift
allanh0526
 
PDF
Automatic reference counting in Swift
allanh0526
 
PDF
Core data in Swfit
allanh0526
 
PDF
From android/java to swift (3)
allanh0526
 
PDF
From android/ java to swift (2)
allanh0526
 
PDF
From android/java to swift (1)
allanh0526
 
PDF
WebRTC
allanh0526
 
PDF
Pipeline interface
allanh0526
 
PDF
Deploying artifacts to archiva
allanh0526
 
PPT
Android httpclient
allanh0526
 
Digital authentication
allanh0526
 
Integration of slather and jenkins
allanh0526
 
How to generate code coverage reports in xcode with slather
allanh0526
 
Unit testing in xcode 8 with swift
allanh0526
 
Ui testing in xcode
allanh0526
 
Using a model view-view model architecture for iOS apps
allanh0526
 
iOS architecture patterns
allanh0526
 
ThingMaker in Swift
allanh0526
 
Automatic reference counting in Swift
allanh0526
 
Core data in Swfit
allanh0526
 
From android/java to swift (3)
allanh0526
 
From android/ java to swift (2)
allanh0526
 
From android/java to swift (1)
allanh0526
 
WebRTC
allanh0526
 
Pipeline interface
allanh0526
 
Deploying artifacts to archiva
allanh0526
 
Android httpclient
allanh0526
 
Ad

Recently uploaded (20)

PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
Ad

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