-3

I use this code to get the current date

let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy.MM.dd"
let result = formatter.string(from: date)

Any idea on how can I get the date in the past, for example a day or a year before the current date?

J.Doe
  • 697
  • 2
  • 16
  • 26

1 Answers1

0

Try to use this:

Date(timeIntervalSinceNow: -3600); \\One hour

Or you can use Calendar for this

let calendar = Calendar.current
var component = DateComponents()
component.year = -1
calendar.date(byAdding: component, to: Date())
Sergey
  • 1,589
  • 9
  • 13
  • Do not use the first option. It will be wrong in some cases. – rmaddy Mar 22 '17 at 14:08
  • @rmaddy Can you provide examples for this case? – Sergey Mar 22 '17 at 14:11
  • Typically you run into issues around daylight saving time and around periods with leap seconds. It's always best to use the `Calendar` methods for doing date arithmetic. – rmaddy Mar 22 '17 at 14:12
  • But for GMT time zone daylight saving time don't have affect. So I don't see any problem with first solution. Only If you want add couple of month or years to date, because months have a different count of days. – Sergey Mar 22 '17 at 14:19
  • 1
    I'm making a general statement that it is always best to use the `Calendar` approach to do date math. It will always be correct. Simply adding or subtracting a number of seconds may or may not be correct. – rmaddy Mar 22 '17 at 14:22