29

这是一个非常简单的概念,但到目前为止,我还没有找到一个优雅的(并且独立于日历区域设置)的解决方案。我需要找到该月的第一天以获取任意NSDate. 例如,给定一个任意的NSDate( arbitraryDate) 将返回另一个 NSDate 对象(我们称之为 this firstDayOfMonthDate),它表示arbitraryDate. 时间部分无关紧要,因为我只需要一个月的第一天的 NSDate 对象(尽管为了简洁起见,如果时间刚刚清零会很有用)。

提前感谢您的任何帮助。

4

5 回答 5

72

一个可能的解决方案:

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];
于 2010-09-16T10:32:22.603 回答
8
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]]);
于 2013-11-07T13:46:47.770 回答
4

斯威夫特 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)!
    }
}
于 2016-10-07T16:23:15.090 回答
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)!
于 2017-06-28T17:30:41.293 回答
1

斯威夫特版本

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)
于 2016-02-01T01:13:43.447 回答