¿Recibe el primer día, el último del mes?

Quiero get firstdate, lastdate of month, bash

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]]; [components setDay:1]; self.currentDate = [calendar dateFromComponents:components]; int m = components.month; int y = components.year; int d = components.day; log: 2012,5,1 

¿Cómo puedo get lastdate od mes?

por favor dame un consejo, gracias !!

Algunos methods de la categoría NSDate que escribí le ayudarán a:

Aquí hay una manera fácil de encontrar el comienzo de un mes:

  (NSDate *) startOfMonth { NSCalendar * calendar = [NSCalendar currentCalendar]; NSDateComponents * currentDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: self]; NSDate * startOfMonth = [calendar dateFromComponents: currentDateComponents]; return startOfMonth; } 

Todo lo que hace es tomar los componentes de año y mes del día actual, luego volver a convertir a una date nuevamente.

Para el final del mes, utilizo un par de methods:

 - (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd { NSCalendar * calendar = [NSCalendar currentCalendar]; NSDateComponents * months = [[NSDateComponents alloc] init]; [months setMonth: monthsToAdd]; return [calendar dateByAddingComponents: months toDate: self options: 0]; } 

y

 - (NSDate *) endOfMonth { NSCalendar * calendar = [NSCalendar currentCalendar]; NSDate * plusOneMonthDate = [self dateByAddingMonths: 1]; NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate]; NSDate * endOfMonth = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month return endOfMonth; } 

Este es un process de 3 pasos: agregue un mes a la date actual, encuentre el comienzo del próximo mes y luego reste 1 segundo para encontrar el final de este mes.


Swift 3

 extension Date { func startOfMonth() -> Date? { let calendar = Calendar.current let currentDateComponents = calendar.dateComponents([.year, .month], from: self) let startOfMonth = calendar.date(from: currentDateComponents) return startOfMonth } func dateByAddingMonths(_ monthsToAdd: Int) -> Date? { let calendar = Calendar.current var months = DateComponents() months.month = monthsToAdd return calendar.date(byAdding: months, to: self) } func endOfMonth() -> Date? { guard let plusOneMonthDate = dateByAddingMonths(1) else { return nil } let calendar = Calendar.current let plusOneMonthDateComponents = calendar.dateComponents([.year, .month], from: plusOneMonthDate) let endOfMonth = calendar.date(from: plusOneMonthDateComponents)?.addingTimeInterval(-1) return endOfMonth } } 

Swift 2

 extension NSDate { func startOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() let currentDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: self) let startOfMonth = calendar.dateFromComponents(currentDateComponents) return startOfMonth } func dateByAddingMonths(monthsToAdd: Int) -> NSDate? { let calendar = NSCalendar.currentCalendar() let months = NSDateComponents() months.month = monthsToAdd return calendar.dateByAddingComponents(months, toDate: self, options: nil) } func endOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() if let plusOneMonthDate = dateByAddingMonths(1) { let plusOneMonthDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: plusOneMonthDate) let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1) return endOfMonth } return nil } } 

Prueba este truco.

Day Param: 1 es get la primera date de este mes

Día Param: 0 es Obtener la última date de este mes al get la última date del mes anterior al mes siguiente (significa este mes))

 - (void)returnDate:(NSDate *)date { NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit; NSDateComponents *comps = [calendar components:unitFlags fromDate:date]; NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1]; NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0]; NSLog(@"date %@", date); // date 2013-06-20 NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01 NSLog(@"Last %@", lastDateOfMonth); // lastDateOfMonth 2013-06-30 } 

Siguiente

 - (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day { NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:day]; [components setMonth:month]; [components setYear:year]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; return [gregorian dateFromComponents:components]; } 

No te olvides de Date Formater

Actualizado para IOS 8.0

 - (void)returnDate:(NSDate *)date { NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth; NSDateComponents *comps = [calendar components:unitFlags fromDate:date]; NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1]; NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0]; NSLog(@"date %@", date); // date 2013-06-20 NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01 NSLog(@"Last %@", lastDateOfMonth); // lastDateOfMonth 2013-06-30 } 

Siguiente

 - (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day { NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:day]; [components setMonth:month]; [components setYear:year]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; return [gregorian dateFromComponents:components]; } 

Ahora está trabajando con:

  • NSCalendarUnitYear
  • NSCalendarUnitWeekOfMonth
  • NSCalendarIdentifierGregorian

Ok, ya que estoy rodando mi propio control de calendar, seguí adelante y creé una categoría de NSCalendar . Aquí está mi método lastOfMonth :

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

Para que Swift 2.0 obtenga el primer día del mes en curso:

  let date = NSDate() let calendar = NSCalendar.currentCalendar() let dateComponents = calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date) let firstDay = self.returnDateForMonth(dateComponents.month, year: dateComponents.year, day: 1) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MMM-yy" print("First day of this month: \(firstDay)") // 01-Sep-15 

Y la function para hacer esto:

  func returnDateForMonth(month:NSInteger, year:NSInteger, day:NSInteger)->NSDate{ let comp = NSDateComponents() comp.month = month comp.year = year comp.day = day let grego = NSCalendar.currentCalendar() return grego.dateFromComponents(comp)! } 

Puede get la última date del mes usando:

 NSDate currDate=[NSDate date]; -(NSString *)getLastDateMonth:(NSDate *)currDate{ NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate]; NSInteger month=[components month]; NSInteger year=[components year]; if (month==12) { [components setYear:year+1]; [components setMonth:1]; } else { [components setMonth:month+1]; } [components setDay:1]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateStyle:NSDateFormatterShortStyle]; NSString *lastDateOfMonth = [dateFormat stringFromDate:(NSDate *)[[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:-86400]]; dateFormat=nil; return lastDateOfMonth; } 

En Swift basado en la respuesta de Nazir

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