3

I want to get the date / time an hour before a given date / time.

Let's say the given date / time is 2012-11-25 13:20:35 (YYYY-mm-dd hour:minute:second).

Jim
  • 72,985
  • 14
  • 101
  • 108
Soumalya Banerjee
  • 1,966
  • 3
  • 22
  • 28
  • If you can get the epoch time (I'm not familiar with this language), you can subtract 3600 from it to get the hour prior. – Josh Sep 14 '12 at 07:50
  • http://stackoverflow.com/questions/5934873/calculating-time-difference-in-objective-c – amitchhajer Sep 14 '12 at 07:50
  • 1
    maybe helpful: http://stackoverflow.com/questions/1160977/how-does-one-subtract-hours-from-an-nsdate – matzino Sep 14 '12 at 07:51
  • Try this: http://stackoverflow.com/questions/6158299/how-to-get-the-date-a-week-in-the-past-from-today/6158401#6158401 – Desdenova Sep 14 '12 at 07:56

2 Answers2

15

You should read Date and Time Programming Guide in the Apple documentation.

Here's something to get you on your way:

NSTimeInterval secondsPerHour = 60 * 60;
NSDate *givenDate = ...; // what you have already
NSDate *earlierDate = [givenDate dateByAddingTimeInterval:-secondsPerHour];

Note the minus sign in front of secondsPerHour, since it's earlier.

Jere Käpyaho
  • 1,305
  • 1
  • 10
  • 29
  • 2
    This should be the accepted answer. – João Pereira Jul 01 '15 at 10:36
  • 1
    I think OP was just marking as accepted which one was earlier, they are similar enough that it's easy for any coder to see which params to replace w/ their own date variable. I upvoted both for good measure though – Albert Renshaw Nov 30 '20 at 04:01
10

you can use:

NSDate *minusOneHr = [[NSDate date] dateByAddingTimeInterval:-60*60];
Casabian
  • 308
  • 2
  • 8
  • 4
    Gives one hour before the current time, not before a given time, unlike my answer which the asker has just unaccepted. – Jere Käpyaho Sep 18 '12 at 11:25