17

月の初日、最終日を取得したい,やってみる

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

lastdate od month を取得するにはどうすればよいですか?

アドバイスをください、ありがとう!!

4

8 に答える 8

1

:- を使用して、月の最終日を取得できます。

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;
}
于 2012-05-23T09:59:48.180 に答える
1

Nazirの回答に基づくSwift

        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)
        }
于 2015-10-23T21:50:11.497 に答える