Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate for first day of the month

This is quite a simple concept, but as of yet I have been unable to find an elegant (and calendar locale independent) solution. I need to find the first day of the month for an arbitrary NSDate. For example, given an arbitrary NSDate (arbitraryDate) another NSDate object will be returned (let's call this firstDayOfMonthDate) which represents the first day of the month in arbitraryDate. The time component does not matter, as I just need the NSDate object for the first day of the month (although for neatness it would be useful if the time was just zeroed out).

Thanks in advance for any assistance.

like image 605
Skoota Avatar asked Sep 16 '10 10:09

Skoota


3 Answers

A possible solution:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *arbitraryDate = [NSDate date];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:arbitraryDate];
[comp setDay:1];
NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];
like image 194
diciu Avatar answered Nov 06 '22 00:11

diciu


NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear 
                                                               fromDate:[NSDate date]];
components.day = 1;
NSDate *firstDayOfMonthDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of month: %@", [firstDayOfMonthDate descriptionWithLocale:[NSLocale currentLocale]]);
like image 31
falsecrypt Avatar answered Nov 06 '22 00:11

falsecrypt


Swift 3

I've included getting the last day of the month in case it is useful to anyone.

extension Date {
    func lastDayOfMonth() -> Date {
        let calendar = Calendar.current
        let dayRange = calendar.range(of: .day, in: .month, for: self)
        let dayCount = dayRange!.count
        var comp = calendar.dateComponents([.year, .month, .day], from: self)

        comp.day = dayCount

        return calendar.date(from: comp)!
    }

    func firstDayOfMonth() -> Date {
        let calendar: Calendar = Calendar.current
        var components: DateComponents = calendar.dateComponents([.year, .month, .day], from: self)
        components.setValue(1, for: .day)
        return calendar.date(from: components)!
    }
}
like image 4
Chris Byatt Avatar answered Nov 06 '22 01:11

Chris Byatt