it-swarm.com.ru

Получение последнего дня месяца

Как я могу получить последний день текущего месяца как NSDate?

49
pradox
NSDate *curDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

// set last of month
[comps setMonth:[comps month]+1];
[comps setDay:0];
NSDate *tDateMonth = [calendar dateFromComponents:comps];
NSLog(@"%@", tDateMonth);

также должен работать.

70
Jonas Schnelli
// Adapted from running code in my app

NSDate *curDate = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSRange daysRange = 
[currentCalendar 
 rangeOfUnit:NSDayCalendarUnit 
 inUnit:NSMonthCalendarUnit 
 forDate:curDate];

// daysRange.length will contain the number of the last day
// of the month containing curDate

NSLog(@"%i", daysRange.length);
41
StCredZero

Поместите это в категорию:

-(NSDate*)lastDayOfMonth
{
    NSInteger dayCount = [self numberOfDaysInMonthCount];

    NSDateComponents *comp = [[self calendar] components:
                              NSCalendarUnitYear |
                              NSCalendarUnitMonth |
                              NSCalendarUnitDay fromDate:self];

    [comp setDay:dayCount];

    return [[self calendar] dateFromComponents:comp];
}

-(NSInteger)numberOfDaysInMonthCount
{
    NSRange dayRange = [[self calendar] rangeOfUnit:NSCalendarUnitDay
                                             inUnit:NSCalendarUnitMonth
                                            forDate:self];

    return dayRange.length;
}

-(NSCalendar*)calendar
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:TIMEZONE]];
    return calendar;
}
9
user1951992

Swift версия

extension NSDate {
    func lastDayOfMonth() -> NSDate {
        let calendar = NSCalendar.currentCalendar()
        let dayRange = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self)
        let dayCount = dayRange.length
        let comp = calendar.components([.Year, .Month, .Day], fromDate: self)

        comp.day = dayCount

        return calendar.dateFromComponents(comp)!
    }
}
3
SoftDesigner

С Swift 3 и iOS 10 самый простой способ сделать это - Calendar 's dateInterval(of:for:) :

func monthInterval() -> DateInterval? {
    let calendar = Calendar.current
    guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return nil }
    let duration = interval.duration
    // Subtract one second because dateInterval(of:for:)'s end date returns the beginning of the following month
    return DateInterval(start: interval.start, duration: duration - 1)
}

guard let interval = monthInterval() else { return }

Затем вы можете использовать interval.start и interval.end, чтобы получить нужные вам даты.

0
LuisCien

Версия Swift 3.0.1

extension Date {
func lastDayOfMonth() -> Date {
    let calendar = NSCalendar.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)!
    }
}
0
burakyldz

Версия от iOS 7

просто чтобы избавиться от обесценивания ... с небольшим дополнением, чтобы получить последнюю секунду дня.

    // current date
    NSDate *now = [NSDate new];

    // get last day of the current month
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [calendar setTimeZone:[NSTimeZone systemTimeZone]];

    NSRange dayRange = [ calendar rangeOfUnit:NSCalendarUnitDay
                                       inUnit:NSCalendarUnitMonth
                                      forDate:now];

    NSInteger numberOfDaysInCurrentMonth = dayRange.length;

    NSDateComponents *comp = [calendar components:
                              NSCalendarUnitYear |
                              NSCalendarUnitMonth |
                              NSCalendarUnitDay fromDate:now];

    comp.day = numberOfDaysInCurrentMonth;
    comp.hour = 24;
    comp.minute = 0;
    comp.second = 0;

    NSDate *endOfMonth = [calendar dateFromComponents:comp];
0
lucianoenrico