Search code examples
objective-cnsdatenscalendarnsdatecomponents

NSCalendar add half a month to an NSDate


I'm trying to determine payment schedules when there are 24 payments per year (i.e. twice per month). The payments aren't going to always be 1st and 15th. I have to start with a given day, and then calculate twice monthly payments starting from there.

NSCalendar and NSDateComponents only have the ability to add integer days, weeks, months, etc. What I really need to do is be able to add 0.5 months, but it only handles integers. I can't just add 15 days, because months have different numbers of days (which is part of the magic that NSCalendar is supposed to handle for us). The first payment of the month should be on the say day per month, so if the payments begin on the 8th, then every odd payment should be on the 8th and every even payment should be on the 8th + half a month. That's where complication comes in. I figure at the very least I can use month addition to get all of the odd numbered payments. Getting the date for those even numbered payments is the difficult part.

Is there a way to add half a month via the NSCalendar that I'm missing? If not, do you have an elegant solution for generating these 24 dates per year?


Solution

  • Well, if you can calculate a date that is 1 month from the start date, calculating half a month is only one division away:

    NSTimeInterval oneMonthInterval = [oneMonthLater timeIntervalSinceDate:startDate];
    NSTimeInterval halfMonthInterval = oneMonthInterval / 2.0;
    NSDate *halfAMonthLater = [startDate dateByAddingTimeInterval:halfMonthInterval];