Search code examples
objective-c

Getting NSDate of yesterday at 12:00 and tonight


Let's say it's now morning in my place 10:00AM. I need to get 2 NSDates, one of yesterday (or today) night at 12:01, and the other of today at 11:59 at night.

I have seen here something like this:

NSDate *today = [NSDate date];
//intervals taken from Google
NSDate *yesterday = [today dateByAddingTimeInterval: -86400.0];

But this number is a const. How would I subtract from now's date what is needed to get today's 12:01 at night (past) and today's 11:59 at night (future)?


Solution

  • You write your own logic as you need

    You will get the NSDate components using

    NSDate *date = [NSDate date]; NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date]; NSInteger day = [components day]; NSInteger month = [components month]; NSInteger year = [components year]; NSInteger hours = [components hour]; NSInteger mins = [components minute]; NSInteger secs = [components second];

    Now you can change the hours and mins a

    hours -= 10; mins -= 120

    Now again the form the date object

    [date setHour:hours]; [date setMinute:mins];