how to add time in current time

后端 未结 4 2014
梦如初夏
梦如初夏 2021-02-14 07:14

I\'m quite confused about this one.

I want to grab, current time, than according to condition, I want to add the required time, to the current time. for example.

相关标签:
4条回答
  • 2021-02-14 07:40

    Swift version:

    let now = NSDate().timeIntervalSince1970 // current time
    let timeAfterXInterval = NSDate().dateByAddingTimeInterval(XXX).timeIntervalSince1970 // time after x sec
    

    XXX is time in sec

    0 讨论(0)
  • 2021-02-14 07:41

    You should not use #define kOneDay 86400

    In timezones that have daylight saving, each year there is one day that only has 82800 seconds, and one day that has 90000 seconds.
    And sometimes there is even a day that has 86401 seconds. (But I think the leap second is ignored by NSDateComponents too.)

    If you want to do it right you should use NSDateComponents.

    to add one day you use it like this:

    NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
    [offset setDay:1];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
    

    it is important to use setDay:1 and not setHour:24.


    to add two weeks and three hours you would use this

    NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
    [offset setWeek:2];
    [offset setHour:3];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
    

    You should get the idea. Start with the biggest unit of change and work your way down to the smallest.

    Yes, it's a little bit more work than addTimeInterval: but addTimeInterval:hours*60*60 is wrong if you care for days, weeks and months.

    0 讨论(0)
  • 2021-02-14 07:47
    'addTimeInterval:' is deprecated
    

    You can use this now

    mydate=[NSDate date];    
    mydate = [mydate dateByAddingTimeInterval:XXX]; //XXX in seconds
    
    0 讨论(0)
  • 2021-02-14 07:53

    Do you mean current time, as in now?

    If so, this will do it for you:

    NSDate *now = [NSDate date]; // Grab current time
    NSDate *newDate = [now addTimeInterval:XXX] // Add XXX seconds to *now
    

    Where XXX is the time in seconds.

    0 讨论(0)
提交回复
热议问题