1

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.

  • If you need the date having only the start date and the amount of days, the native Date of swift actually has a method addingTimeInterval(timeInterval) that you can use to get the date you need. – Ben Ong Dec 07 '16 at 08:57
  • However I do not understand what you meant by "how to change specific days in second loop", you might want to post the codes for the two loops for me to understand how you even approached this problem to begin with – Ben Ong Dec 07 '16 at 08:58
  • @BenOng Please suggest how can i do this? – ankur kumawat Dec 07 '16 at 09:00
  • I have many dictionary and in this dictionary define days like "sunday, monday" so how to find particular weekdays with date between two dates – ankur kumawat Dec 07 '16 at 09:03
  • @BenOng Please help – ankur kumawat Dec 07 '16 at 09:05
  • Create new mutiable Array and put all dict into it. Then [checkhere](http://stackoverflow.com/questions/9529620/sort-nsdictionary-keys-as-nsdate) – Rin Dec 07 '16 at 09:05
  • The native Date have a method timeIntervalSince, you can create a Date using the start date then invoke timeIntervalSince passing enddate as the parameter to find out how many weeks there is between the two dates. Note that the timeInterval you get in return is in seconds, you need to do some math yourself. – Ben Ong Dec 07 '16 at 09:09
  • Before you run the loop to get the exact dates you need to determine which days are "none", I'd recommend creating an array of 7 BOOL and set each to true or false based on the comparison result. – Ben Ong Dec 07 '16 at 09:13
  • During the loop, you just have to add the amount of days between each day using the method addingTimeInterval from the startdate to get the exact date for each day you want – Ben Ong Dec 07 '16 at 09:15
  • @BenOng please explain some code because i am so confused in loop – ankur kumawat Dec 07 '16 at 09:16
  • First of all you should consolidate your data e.g. the two different date formats. If you parse `25-11-16` with `yyyy` you will get `25.11.0016` – vadian Dec 07 '16 at 10:01
  • @vadian How to get my output – ankur kumawat Dec 07 '16 at 10:03
  • Ben's answer is a good point to start with. – vadian Dec 07 '16 at 10:09
  • @vadian please Ben's swift code convert to ObjC, I tried but do not convert – ankur kumawat Dec 07 '16 at 10:37

2 Answers2

0
extension Date {

    static func generateDatesArrayBetweenTwoDates(startDate: Date, endDate: Date) -> [Date] {
        var datesArray: [Date] = [Date]()
        var startDate = startDate
        let calendar = Calendar.current
        while startDate <= endDate {
            let tempDate = self.dateFormatter().string(from: startDate)
            datesArray.append(self.dateFormatter().date(from: tempDate) ?? Date())
            startDate = calendar.date(byAdding: .day, value: 1, to: startDate)! 
        }
        return datesArray
    }

    static func dateFormatter() -> DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }

}

Get number of specific days

func getDates() {
        var count = 0
        let tempStartDate = Date.dateFormatter().string(from: Date())
        guard let startDate = Date.dateFormatter().date(from: tempStartDate) else {
            return
        }
        let tempEndDate = Date.dateFormatter().string(from: Date(timeIntervalSince1970: 1575181456)) // lets say 1st dec 2019
        guard let endDate = Date.dateFormatter().date(from: tempEndDate) else {
            return
        }
        let datesArray = Date.generateDatesArrayBetweenTwoDates(startDate: endDate, endDate: startDate)
        for date in datesArray {
            let calendar = Calendar(identifier: .gregorian)
            let components = calendar.dateComponents([.weekday], from: date)
            if components.weekday == 6 { // For friday check
                count += 1
                print("Hello Friday")
            } else {
                print("It's not Friday")
            }
        }
        print("number of fridays", count)
    }

Hope it helps

Pooja Gupta
  • 313
  • 2
  • 9
-1

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.

Ben Ong
  • 913
  • 1
  • 10
  • 25
  • And if you need help with logic it will always be better to show what you already have, I did a large amount of assumptions in this code which should not happen in an actual situation – Ben Ong Dec 07 '16 at 09:39
  • Sorry for late replay, Please convert in ObjC. because your code not usable and my commend in ObjC. – ankur kumawat Dec 07 '16 at 10:04
  • 1
    Please don't make me type your codes for you, you can use that logic to create you codes. The function and parameter names will be largely similar, that logic will help you sufficiently to get your results. – Ben Ong Dec 07 '16 at 10:06
  • ok please wait a minute because i convert your code. and thanks for give your precious time. – ankur kumawat Dec 07 '16 at 10:12
  • 1
    note, that this code will yield errors because of day light saving times, as days can have 23, 24 or 25 hours. Never use 86400 seconds for a day, but use the NSCalendar api. – vikingosegundo Dec 08 '16 at 05:32
  • I apologise that I do not get affected by DST so I need not consider it for calculation, please make sure that you do make such considerations if your app is to be used where DST affects – Ben Ong Dec 08 '16 at 05:41
  • So how would somebody take such consideration in account, given that DST is different in different timezones, different in countries within this timezones and even for different cities. And those information change from year to year? Should they include a long table with those information? – vikingosegundo Dec 08 '16 at 05:46
  • I only know as far as that you can get the current country the user is in from the device itself either by the user's settings or the location. As for how each country calculate their DST and how it defers... that is beyond me – Ben Ong Dec 08 '16 at 06:23
  • But what I do know is that ultimately DST only shifts by one hour and resets once the period is over, so if you start the calculation from midday, minimally you can get the correct date, just not the correct hour – Ben Ong Dec 08 '16 at 06:24
  • I went to read around [this answer](http://stackoverflow.com/questions/27053135/how-to-get-a-users-time-zone) actually tells how to get DST – Ben Ong Dec 08 '16 at 06:27
  • Just rely on foundations API, namely NSCalendar. watch [WWDC 2011 Video "Session 117 - Performing Calendar Calculations"](https://developer.apple.com/videos/play/wwdc2011/117/). As soon as you use the infamous constant 86400, you are on the wrong track. – vikingosegundo Dec 12 '16 at 02:48