Get firstdate, lastdate of month?

后端 未结 8 1005
不思量自难忘°
不思量自难忘° 2021-02-01 21:29

I want to get firstdate、lastdate of month,I try

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.c         


        
相关标签:
8条回答
  • 2021-02-01 22:03

    Swift 5 getting last day of month - base on different sources

    // -------------------------------------------------------
    // lastDayOfMonth
    // -------------------------------------------------------
    static func lastDayOfMonth(year:Int, month:Int) -> Int {
        let calendar:Calendar = Calendar.current
        var dc:DateComponents = DateComponents()
        dc.year = year
        dc.month = month + 1
        dc.day = 0
        let lastDateOfMonth:Date = calendar.date(from:dc)!
        let lastDay = calendar.component(Calendar.Component.day, from: lastDateOfMonth)
        return lastDay
    }
    
    0 讨论(0)
  • 2021-02-01 22:04

    For Swift 2.0 to get the first day of the current month:

        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
    

    And the function to do this:

     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)!
    }
    
    0 讨论(0)
  • 2021-02-01 22:05

    Some NSDate category methods I wrote will help you:

    Here's an easy way to find the start of a month:

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

    All it does is take the year and month components from the current day, then convert back to a date again.

    For the end of the month, I use a couple of 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];
    }
    

    and

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

    This is a 3 step process - add one month to the current date, find the start of the next month, then subtract 1 second to find the end of this month.


    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
        }
    }
    
    0 讨论(0)
  • 2021-02-01 22:06

    You can get last date of month using :-

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 22:11

    Try this trick.

    Day Param: 1 is to Get first date of this month

    Day Param: 0 is to Get last date of this month by getting last date of month previous to next month (means this month))

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

    Next

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

    Don't forget for right Date Formater

    Updated for 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
    
    }
    

    Next

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

    Now your are working with:

    • NSCalendarUnitYear
    • NSCalendarUnitWeekOfMonth
    • NSCalendarIdentifierGregorian
    0 讨论(0)
  • 2021-02-01 22:17

    Looks like there is no need for any tricks or hacks, NSCalendar's rangeOfUnit does the job pretty nicely:

    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDateComponents *dc = [[NSDateComponents alloc] init];
    dc.year = 1947;
    dc.month = 8; //desired month
    
    //calculate start date
    dc.day = 1; //As far as I can think start date of a month will always be 1
    NSDate *start = [cal dateFromComponents:dc];
    
    //calculate last date of month
    NSRange dim = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:start]; // we used start date as it has the same month & year value as desired
    dc.day=dim.length; //this is the simply the last day of the desired month
    NSDate *last = [[NSCalendar currentCalendar] dateFromComponents:dc];
    

    Log the values for verification:

    NSLog(@"Start day of month Date: %@", start);
    NSLog(@"Last day of month Date: %@", last);
    

    Apple docs on NSCalendar rangeOfUnit: https://developer.apple.com/documentation/foundation/nscalendar/1418344-rangeofunit

    p.s looks like this uses the same logic as @Scott Means's answer, but doesn't require any category, so use which ever answer you prefer!

    0 讨论(0)
提交回复
热议问题