简体   繁体   English

获取ios sdk中当月星期一的所有日期

[英]Get all the date of the monday of current month in ios sdk

How to get all the date of all the monday in current month in ios sdk? 如何获取ios sdk当月所有星期一的所有日期?

For example i want date of all the monday occur in January-2015 例如,我希望所有星期一的日期发生在2015年1月

Below code give me month,day and year from nsdate. 下面的代码给出了nsdate的月,日和年。 But now i want nsdate of weekday(Monday) in that month. 但是现在我想要那个月的工作日(星期一)的nsdate。

NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; // Get necessary date components

 [components month]; //gives you month
 [components day]; //gives you day
 [components year]; // gives you year
//Set Wantedday here with sun=1 ..... sat=7;
NSInteger wantedWeekDay = 2; //for monday

//set current date here
NSDate *currentDate = [NSDate date];

//get calender
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Start out by getting just the year, month and day components of the current date.
NSDateComponents *components = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSCalendarUnitWeekday fromDate:currentDate];
// Change the Day component to 1 (for the first day of the month), and zero out the time components.
[components setDay:1];

[components setHour:0];
[components setMinute:0];
[components setSecond:0];

//get first day of current month
NSDate *firstDateOfCurMonth = [gregorianCalendar dateFromComponents:components];

//create new component to get weekday of first date
NSDateComponents *newcomponents = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSCalendarUnitWeekday fromDate:firstDateOfCurMonth];
NSInteger firstDateWeekDay = newcomponents.weekday;
NSLog(@"weekday : %li",(long)firstDateWeekDay);

//get last month date
NSInteger curMonth = newcomponents.month;
[newcomponents setMonth:curMonth+1];

NSDate * templastDateOfCurMonth = [[gregorianCalendar dateFromComponents:newcomponents] dateByAddingTimeInterval: -1]; // One second before the start of next month

NSDateComponents *lastcomponents = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSCalendarUnitWeekday fromDate:templastDateOfCurMonth];

[lastcomponents setHour:0];
[lastcomponents setMinute:0];
[lastcomponents setSecond:0];

NSDate *lastDateOfCurMonth = [gregorianCalendar dateFromComponents:lastcomponents];

NSLog(@"%@",lastDateOfCurMonth);

NSMutableArray *mutArrDates = [NSMutableArray array];

NSDateComponents *dayDifference = [NSDateComponents new];
[dayDifference setCalendar:gregorianCalendar];

//get wanted weekday date
NSDate *firstWeekDateOfCurMonth = nil;
if (wantedWeekDay == firstDateWeekDay) {
    firstWeekDateOfCurMonth = firstDateOfCurMonth;
}
else
{
    NSInteger day = wantedWeekDay - firstDateWeekDay;
    if (day < 0)
        day += 7;
    ++day;
    [components setDay:day];

    firstWeekDateOfCurMonth = [gregorianCalendar dateFromComponents:components];
}

NSLog(@"%@",firstWeekDateOfCurMonth);

NSUInteger weekOffset = 0;
NSDate *nextDate = firstWeekDateOfCurMonth;

do {
    [mutArrDates addObject:nextDate];
    [dayDifference setWeekOfYear:++weekOffset];
    NSDate *date = [gregorianCalendar dateByAddingComponents:dayDifference toDate:firstWeekDateOfCurMonth options:0];
    nextDate = date;
} while([nextDate compare:lastDateOfCurMonth] == NSOrderedAscending || [nextDate compare:lastDateOfCurMonth] == NSOrderedSame);

NSLog(@"%@",mutArrDates);

The basic steps 基本步骤

  1. Create an NSDate object for the first day of that month (eg, 1/1/2015) 为该月的第一天创建NSDate对象(例如,2015年1月1日)
  2. Determine the day of the week for that date 确定该日期的星期几
  3. Offset the day to the day of week you are interested in 将您感兴趣的一天抵消到当天
  4. Add 7 to the day until you reach the end of the month 添加7到当天,直到您到月底

Here's an example of how to do that 这是一个如何做到这一点的例子

- (NSArray *) datesForWeekday:(NSInteger)weekday forMonth:(NSInteger)month andYear:(NSInteger)year
{
    unsigned int units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                        | NSCalendarUnitWeekday;
    // Step 1. create an NSDate for the first of the month
    NSDate *date = [self dateWithMonth:month day:1 andYear:year];

    // Step 2. determine the day of the week (1=Sunday, 2=Monday, ..., 7=Saturday
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:date];
    NSInteger firstDayOfMonth = [comps weekday];

    // Step 3. offset so the day is the day of the week you are interested in
    NSInteger day = weekday - firstDayOfMonth;
    if (day < 0)
        day += 7;
    ++day;

    NSMutableArray *array = [NSMutableArray new];

    NSUInteger numberOfDaysInMonth = [self numberOfDaysWithDate:date];
    // Step 4. add 7 to the day until we reach the end of the month
    do {
        // Add NSDate object to array
        [array addObject:[self dateWithMonth:month day:day andYear:year]];

        // or you can optionally add just the day to the array
        // [array addObject:@(day)];

        day += 7;
    } while (day <= numberOfDaysInMonth);
    return array;
}

// Returns an NSDate object for the specified month, day, and year
- (NSDate *) dateWithMonth:(NSInteger)month day:(NSInteger)day andYear:(NSInteger)year
{
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:day];
    [dateComps setMonth:month];
    [dateComps setYear:year];
    [dateComps setHour:0];
    [dateComps setMinute:0];
    return [[NSCalendar currentCalendar] dateFromComponents:dateComps];
}

// Determines the number of days in the month for specified date
- (NSUInteger) numberOfDaysWithDate:(NSDate *)date
{
    NSRange days = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay
                           inUnit:NSCalendarUnitMonth
                          forDate:date];
    return days.length;
}

Here's an example of how find all Mondays in January of 2015 以下是2015年1月查找所有星期一的示例

NSArray *dates = [self datesForWeekday:2 forMonth:1 andYear:2015];

or all the Wednesdays in December 2018 或2018年12月的所有星期三

NSArray *dates = [self datesForWeekday:4 forMonth:12 andYear:2018];

or all Mondays in the current month 或本月的所有星期一

NSDate *date = [NSDate date];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:date];
NSArray *dates = [self datesForWeekday:2 forMonth:[comps month] andYear:[comps year]];

Simple solution using (NS)Calendar and the NSCalendarUnitWeekdayOrdinal component of (NS)DateComponents . 使用(NS)Calendar(NS)DateComponentsNSCalendarUnitWeekdayOrdinal组件的简单解决方案。

Get the components for year , month and weekdayOrdinal of the current date. 获取当前日期的yearmonthweekdayOrdinal的组件。 Then in a loop get all ordinal weekdays until the month component exceeds the current month 然后在循环中获取所有序数的工作日,直到月份组件超过当前月份

Objective-C: Objective-C的:

- (NSArray<NSDate *> *)datesOfCurrentMonthWith:(NSInteger)weekday {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekdayOrdinal  fromDate:[NSDate date]];
    components.weekday = 1;
    NSMutableArray<NSDate *> *result = [NSMutableArray array];

    for (NSInteger ordinal = 1; ordinal < 6; ordinal++) { // maximum 5 occurrences
        components.weekdayOrdinal = ordinal;
        NSDate *date = [calendar dateFromComponents:components];
        if ([calendar component:NSCalendarUnitMonth fromDate:date] != components.month) { break; }
        [result addObject:[calendar dateFromComponents: components]];
    }
    return [result copy];
}

Swift: 迅速:

func datesOfCurrentMonth(with weekday : Int) -> [Date] {
    let calendar = Calendar.current
    var components = calendar.dateComponents([.year, .month, .weekdayOrdinal], from: Date())
    components.weekday = weekday
    var result = [Date]()

    for ordinal in 1..<6 { // maximum 5 occurrences
        components.weekdayOrdinal = ordinal
        let date = calendar.date(from: components)!
        if calendar.component(.month, from: date) != components.month! { break }
        result.append(calendar.date(from: components)!)
    }
    return result
}

Just Pass all Date of Month You Get All Monday!i have create example and it working fine for Current Date! 只需通过所有星期一的所有日期!我已经创建了一个示例,它在当前日期工作正常!

in viewDidLoad 在viewDidLoad中

NSDate *dt = [NSDate date];
NSCalendar *gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components: NSCalendarUnitEra |NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay  fromDate:dt];

NSRange days = [gregorian rangeOfUnit:NSCalendarUnitDay
                       inUnit:NSCalendarUnitMonth
                      forDate:dt];

for (int i=1; i<days.length+1; i++)
{
    comp.day = i;
    if([self isMonday:[gregorian dateFromComponents:comp]])
    {
        NSLog(@"Monday %@",[gregorian dateFromComponents:comp]);
    }
}

-(BOOL)isTodayMonday:(NSDate*)dt
{
    BOOL isMonday;
    NSDateFormatter *datef = [[NSDateFormatter alloc]init];
    datef.dateFormat = @"EEEE";
    NSString *strDate = [datef stringFromDate:dt];
    if([strDate isEqualToString:@"Monday"])
    {
       NSLog(@"monday date %@",dt);
       isMonday = YES;
    }
    else
    {
        isMonday = NO;    
    }
    return isMonday;
}

you can refer that here 你可以在这里参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM