I have been researching, but I couldnt find exact solution for my problem. I have been trying to get 1 hour ago from a date. How can I achieve this in swift?
According to your needs, you may choose one of the 3 following Swift 5 methods to get one hour ago from a Date instance.
date(byAdding:value:to:wrappingComponents:)Calendar has a method called date(byAdding:value:to:wrappingComponents:). date(byAdding:value:to:wrappingComponents:) has the following declaration:
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
Returns a new
Daterepresenting the date calculated by adding an amount of a specific component to a given date.
The Playground code below shows how to use it:
import Foundation
let now = Date()
let oneHourAgo = Calendar.current.date(byAdding: .hour, value: -1, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
date(byAdding:to:wrappingComponents:)Calendar has a method called date(byAdding:to:wrappingComponents:). date(byAdding:value:to:wrappingComponents:) has the following declaration:
func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?
Returns a new
Daterepresenting the date calculated by adding components to a given date.
The Playground code below shows how to use it:
import Foundation
let now = Date()
var components = DateComponents()
components.hour = -1
let oneHourAgo = Calendar.current.date(byAdding: components, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
Alternative:
import Foundation
// Get the date that was 1hr before now
let now = Date()
let components = DateComponents(hour: -1)
let oneHourAgo = Calendar.current.date(byAdding: components, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
addingTimeInterval(_:) (use with caution)Date has a method called addingTimeInterval(_:). addingTimeInterval(_:) has the following declaration:
func addingTimeInterval(_ timeInterval: TimeInterval) -> Date
Return a new
Dateby adding aTimeIntervalto thisDate.
Note that this method comes with a warning:
This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a
Calendar. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
The Playground code below shows how to use it:
import Foundation
let now = Date()
let oneHourAgo = now.addingTimeInterval(-3600)
print(now) // 2016-12-19 21:52:04 +0000
print(oneHourAgo) // 2016-12-19 20:52:04 +0000