SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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中关于日期类的使用指引

Weitere ähnliche Inhalte

Ähnlich wie How to work with dates and times in swift 3

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
 
Datetime - Julian Date
Datetime - Julian DateDatetime - Julian Date
Datetime - Julian Date
Shuo Chen
 

Ähnlich wie 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
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
 
doc
docdoc
doc
 
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
 

Mehr von allanh0526

Mehr von 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
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

How to work with dates and times in swift 3

  • 1. How to work with dates and times in Swift 3 Allan Shih
  • 2. Agenda ● Date and Time programming in Swift 3 ● Date and Time classes ○ Date ○ DateComponents ○ DateFormatter ○ Calendar ○ Locale ○ TimeZone ● Reference
  • 3. Date and time programming in Swift 3 ● Break a date into its components and access each date part separately (day, month, etc). ● Convert between dates and strings ● Compare dates ● Calculate dates in the future or in the past ● Calculate date differences
  • 4. Date and time classes ● Date ○ Represents a single point in time ○ Expressed in seconds before or after midnight, jan 1, 2001 UTC ● DateComponents ○ Represents the parts of a given date ● DateFormatter ○ Convert dates into formatted strings ● String ○ The text representation of a date and time
  • 5. Date and time classes ● Calendar ○ Provides a context for dates and the ability to do date arithmetic ● Locale ○ Represents a users’s regional settings, including those for date and time. ● TimeZone ○ Convert dates into formatted strings
  • 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中关于日期类的使用指引