how to add time in current time

后端 未结 4 2222
清歌不尽
清歌不尽 2021-02-14 07:01

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:59

    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.

提交回复
热议问题