17

我想获取月份的firstdate、lastdate,我试试

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

28

我写的一些NSDate分类方法会对你有所帮助:

以下是查找月份开始的简单方法:

 (NSDate *) startOfMonth
{
    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents * currentDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: self];
    NSDate * startOfMonth = [calendar dateFromComponents: currentDateComponents];

    return startOfMonth;
}

它所做的只是从当天获取年份和月份部分,然后再次转换回日期。

在月底,我使用了几种方法:

- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd
{
    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents * months = [[NSDateComponents alloc] init];
    [months setMonth: monthsToAdd];

    return [calendar dateByAddingComponents: months toDate: self options: 0];
}

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

这是一个 3 步过程 - 将一个月添加到当前日期,找到下个月的开始,然后减去 1 秒以找到本月的结束。


斯威夫特 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

    }
}

斯威夫特 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
    }
}
于 2012-05-23T10:02:58.347 回答
7

试试这个技巧。

Day Param:1 是获取本月的第一个日期

Day Param:0 是通过获取上个月的最后一个日期来获取本月的最后一个日期(表示本月)

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

}

下一个

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

不要忘记正确的日期格式化程序

针对 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

}

下一个

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

现在您正在使用:

  • NSCalendarUnitYear
  • NSCalendarUnitWeekOfMonth
  • NSCalendarIdentifierGregorian
于 2013-04-20T11:57:31.960 回答
3

好的,因为我正在滚动自己的日历控件,所以我继续创建了一个NSCalendar类别。这是我的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];
}
于 2013-06-24T19:06:40.990 回答
2

对于Swift 2.0获取当月的第一天:

    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

以及执行此操作的功能:

 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)!
}
于 2015-09-29T19:06:22.163 回答
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

在基于纳齐尔的回答的斯威夫特

        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 回答
1

Swift 5 得到月的最后一天 - 基于不同的来源

// -------------------------------------------------------
// 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
}
于 2019-11-25T15:12:09.763 回答
0

看起来不需要任何技巧或技巧,NSCalendarrangeOfUnit做得很好:

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

记录值以进行验证:

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

关于 NSCalendar rangeOfUnit 的 Apple 文档:https ://developer.apple.com/documentation/foundation/nscalendar/1418344-rangeofunit

ps 看起来这使用与@Scott Means 的答案相同的逻辑,但不需要任何类别,因此请使用您喜欢的答案!

于 2017-11-09T05:12:03.190 回答