问题描述:

I have two dates StartDate and EndDate. And weekDays, I want to find specific days e.g. Monday, Tuesday, Saturday between these two dates. And how to change specific days in second loop.

I want to add multiple Object in array flow the below code

NSDictionary *dict = @{

@"name": @"kiran",

@"startdate": @"25-11-16",

@"SUNDAY": @"none"

@"MONDAY": @"monday"

@"TUESDAY": @"tuesday"

@"WEDNESDAY": @"none"

@"THURSDAY": @"none"

@"FRIDAY": @"friday"

@"SATURDAY": @"none"

@"EndDate": @"7-12-2016"

};

NSDictionary *dict1 = @{

@"name": @"Bala",

@"startdate": @"1-11-16",

@"SUNDAY": @"sunday"

@"MONDAY": @"none"

@"TUESDAY": @"tuesday"

@"WEDNESDAY": @"none"

@"THURSDAY": @"thursday"

@"FRIDAY": @"friday"

@"SATURDAY": @"none"

@"EndDate": @"7-12-2016"

};

NSDictionary *dict2 = @{

@"name": @"Sri",

@"startdate": @"1-12-16",

@"SUNDAY": @"sunday"

@"MONDAY": @"monday"

@"TUESDAY": @"tuesday"

@"WEDNESDAY": @"wednesday"

@"THURSDAY": @"thursday"

@"FRIDAY": @"friday"

@"SATURDAY": @"saturday"

@"EndDate": @"7-12-2016"

};

NSMutableArray *listMutableArray =[[NSMutableArray alloc] initWithObjects:dict,dict1,dict2, nil];

How can I execute a loop between two dates?

I want output is : first dict

25-11-2016, Friday, kiran

28-11-2016, Monday,kiran

29-11-2016, Tuesday,kiran

2-12-2016, Friday,kiran

5-12-2016, Monday,kiran

6-12-2016, Tuesday,kiran

Same as second and third dict output. and all weekdays store in a single array.

网友答案:

I am more used to swift so I am going to give my answer using swift instead of objC, read it as pseudo codes if you have to use objC for your codes

To get the results you want for say just the first item of the MutableArray

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"

let dict = listMutableArray[0] as Dictionary
let name = dict["name"]
let startDate = dateFormatter.date(from: dict["startdate"])
let endDate = dateFormatter.date(from: dict["enddate"])

let totalDuration = endDate.timeIntervalSince(startDate)
let totalDuration = totalDuration/86400 //to get days from seconds - 86400 = 60*60*24

let weekDaysToCount:Array<Bool> = Array()
if dict["MONDAY"] != "none" {
    weekDaysToCount.append(true)
} else {
    weekDaysToCount.append(false)
}
... ...
//Repeat for all days

for i in 0..<Int(totalDuration) {
    for validDay in weekDaysToCount {
        startDate = startDate.addingTimeInterval(86400) //one day
        if validDay {
            print("\(startDate), \(name)")
        }
    }
}

Note that the weekDaysToCount assumes that starting day is Monday, when the situation is not so you need to adjust the array.

相关阅读:
Top