I want to get firstdate、lastdate of month,I try
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.c
In Swift based in Nazir's answer
func getFirstAndLastDateOfMonth(date: NSDate) -> (fistDateOfMonth: NSDate, lastDateOfMonth: NSDate) {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let calendarUnits = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth
let dateComponents = calendar?.components(calendarUnits, fromDate: date)
let fistDateOfMonth = self.returnedDateForMonth(dateComponents!.month, year: dateComponents!.year, day: 1)
let lastDateOfMonth = self.returnedDateForMonth(dateComponents!.month + 1, year: dateComponents!.year, day: 0)
println("fistDateOfMonth \(fistDateOfMonth)")
println("lastDateOfMonth \(lastDateOfMonth)")
return (fistDateOfMonth!,lastDateOfMonth!)
}
func returnedDateForMonth(month: NSInteger, year: NSInteger, day: NSInteger) -> NSDate? {
var components = NSDateComponents()
components.day = day
components.month = month
components.year = year
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
return gregorian!.dateFromComponents(components)
}
Ok, since I'm rolling my own calendar control, I went ahead and created a NSCalendar
category. Here's my lastOfMonth
method:
- (NSDate *)lastOfMonth:(NSDate *)date
{
NSDateComponents *dc = [self components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];
NSRange dim = [self rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
dc.day = dim.length;
return [self dateFromComponents:dc];
}