ios developer
ios developer

Reputation: 3473

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?

For example i want date of all the monday occur in January-2015

Below code give me month,day and year from nsdate. But now i want nsdate of weekday(Monday) in that month.

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

Upvotes: 5

Views: 3155

Answers (4)

vadian
vadian

Reputation: 285079

Simple solution using (NS)Calendar and the NSCalendarUnitWeekdayOrdinal component of (NS)DateComponents.

Get the components for year, month and weekdayOrdinal of the current date. Then in a loop get all ordinal weekdays until the month component exceeds the current month

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
}

Upvotes: 4

0x141E
0x141E

Reputation: 12753

The basic steps

  1. Create an NSDate object for the first day of that month (e.g., 1/1/2015)
  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

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

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

or all the Wednesdays in December 2018

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

Upvotes: 2

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

//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);

Upvotes: 3

Saurabh Prajapati
Saurabh Prajapati

Reputation: 2380

Just Pass all Date of Month You Get All Monday!i have create example and it working fine for Current Date!

in 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

Upvotes: 0

Related Questions