NSDate为该月的第一天

时间:2010-09-16 10:18:44

标签: iphone cocoa-touch nsdate nscalendar

这是一个非常简单的概念,但到目前为止,我一直无法找到一个优雅的(和日历区域独立的)解决方案。我需要找到任意NSDate的月份的第一天。例如,给定任意NSDatearbitraryDate)将返回另一个NSDate对象(让我们称之为firstDayOfMonthDate),该对象表示arbitraryDate中该月的第一天。时间组件并不重要,因为我只需要在该月的第一天使用NSDate对象(尽管为了整洁,如果时间刚刚归零,它将是有用的。)

提前感谢您的任何帮助。

5 个答案:

答案 0 :(得分:68)

可能的解决方案:

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];

答案 1 :(得分:7)

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]]);

答案 2 :(得分:4)

Swift 3

我已经包括了这个月的最后一天,以防它对任何人都有用。

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)!
    }
}

答案 3 :(得分:1)

Swift版

let arbitraryDate:NSDate = NSDate()
let calendar:NSCalendar = NSCalendar.currentCalendar()
let components:NSDateComponents = calendar.components([.Year, .Month, .Day], fromDate: arbitraryDate)
components.setValue(1, forComponent: .Day)
let firstDayOfMonthDate = calendar.dateFromComponents(components)

答案 4 :(得分:1)

斯威夫特3:

let calendar = Calendar.current
var comps = calendar.dateComponents([.year, .month], from: date)
comps.setValue(1, for: .day)
let firstDayOfMonth = calendar.date(from: comps)!

// I tried this, but it doesn't work, why?
// let firstDayOfMonth = calendar.date(bySetting: .day, value: 1, of: date)!