【问题标题】:Calculating the end of a month, or its last second计算月底或最后一秒
【发布时间】:2011-06-05 20:20:02
【问题描述】:

我有最简单的任务,但我不知道如何正确完成。通过下面的 sn-p,我可以找出月初。

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *beginning = nil;
[cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self];
return beginning;

现在我想确定同一个月的月底(最后一秒 23:59:59 适合我的目的)。我的第一个想法是从下个月的第一天开始,减去一秒钟。但我无法将 NSDateComponent 实例中的日期分解为 [dateComponents setMonth:[dateComponents month] + 1],因为在 12 月的情况下,该方法不会接受 12 + 1 = 13 来到达 1 月,对吧?

那我怎么才能到一个月的最后一秒呢?

【问题讨论】:

  • 但是你确定最后一秒月末吗?那么最后一个毫秒呢?
  • 那也完全没问题。有什么想法吗?

标签: objective-c cocoa nsdate nscalendar nsdatecomponents


【解决方案1】:

这样做以获得下个月的开始:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:1];
NSDate *beginningOfNextMonth = [cal dateByAddingComponents:comps toDate:beginning options:0];
[comps release];

【讨论】:

  • 那就更好了。我正在慢慢适应日期组件的多种用途,谢谢!
  • 要真正获得最后一秒,请在上面添加[comps setSecond:-1];
【解决方案2】:

好吧,我想我知道了。我正在使用rangeOfUnit:inUnit:forDate:方法来确定当前月份的天数,并将对应的NSTimeInterval添加到月份的开始日期。

- (NSDate *)firstSecondOfTheMonth {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *beginning = nil;
    if ([cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self])
        return beginning;
    return nil;
}

- (NSDate *)lastSecondOfTheMonth {
    NSDate *date = [self firstSecondOfTheMonth];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSRange month = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    return [date dateByAddingTimeInterval:month.length * 24 * 60 * 60 - 1];
}

注意:尽管此代码按我的预期工作,但the answer that @spacehunt 更清楚地传达了目的。

【讨论】:

    【解决方案3】:

    本月的最后一秒...大多数情况下,这归结为取下个月的第一秒,然后减去一秒。

    但是你问对了问题吗?最后一秒是什么意思?我的猜测是你想表达一个时间间隔,从 N 月的第一秒(包括)开始,到 N+1 月的第一秒之前结束。

    【讨论】:

    • 好吧,换个说法:我如何才能到下个月的开始?
    • 使用 NSCalendar 的 dateByAddingComponents:toDate:options: 进行日期计算。
    猜你喜欢
    • 2010-09-18
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多