0

I generate 7 dates by adding days to current date. I add all the dates in an Array. Now when I pick any date, it pulls the correct date. Then I create components of that date. Now when I print the component, it show the date(day part) as next day's date. So, if choose 27-05-2016, and then get its components, and when I check, component.day, it gives me 28 instead of 27.

Here is my code to generate dates :

    let cal = NSCalendar.currentCalendar()
    // start with today
    let selectedDate = cal.startOfDayForDate(NSDate())

 for index in 1...7 {

        dateArray.addObject(selectedDate.dateByAddingTimeInterval(Double(index)*24*60*60))

        print(dateArray.objectAtIndex(index-1))

    }

Here is the code where I choose a date from the above array and fetch its components :

 if currentIndexPosition>=0 {

        selectedDate = dateArray.objectAtIndex(currentIndexPosition) as? NSDate
    }
    else
    {
        selectedDate = dateArray.objectAtIndex(0) as? NSDate
    }

    let cal = NSCalendar.currentCalendar()
    let components = cal.components([.Day , .Month, .Year, .Hour,.Minute ], fromDate: selectedDate!)

Now when I check the components the date is not the same that I chose from the array. Its one more than the selected date.

This is what I selected from date array But when I check its components, I get incorrect date

Please let me know , if I missed anything or you need any other info.

Thanks

intellignt_idiot
  • 1,962
  • 2
  • 16
  • 23
  • Check after set date formatter. > Hour and minute also 0. – Payal Maniyar May 26 '16 at 07:58
  • 2
    Indexes in Swift / ObjC start always with zero, maybe there is a confusion, and please **never** do date math using *86400*, there are dedicated (and more reliable) methods like `dateByAddingUnit:value:toDate:options` of NSCalendar. – vadian May 26 '16 at 08:03
  • @PayalManiyar I did not understand , hour and minute are zero, but I do not care about them. I just want the date. I am going to add hour and minute separately. – intellignt_idiot May 26 '16 at 08:07
  • @vadian its not about the adding of days. Its about date showing correct at one place and incorrect at other place (in components) – intellignt_idiot May 26 '16 at 08:08
  • 2
    "2016-05-28 18:30:00 UTC" is *the same point in time* as "2016-05-29 00:00:00" in your time zone! – NSDateComponents contains the values in your local timezone, and the *debugger* displays the date in UTC. There is nothing wrong! (Search for "NSDate wrong" and you'll find many similar issues.) – Martin R May 26 '16 at 08:09
  • But @vadian is right as well: A day does not always have 24 hours, it can be 23 or 25 hours when transitioning from or to daylight savings time. – Martin R May 26 '16 at 08:12
  • @MartinR -- Alright. It means the code is correct. Thanks – intellignt_idiot May 26 '16 at 08:12

0 Answers0