-5

I'm struggling in calculation the days between some dates .

I want to calculate the days until new year or the minutes. I tried a way which I saw on another post here by using dateComponents but I wasn't able to calculate.

If some one can help I would be realy happy.

Thank You !

Umair Aamir
  • 1,624
  • 16
  • 26

1 Answers1

1

It would be helpful to see what you've tried to give some advice, but nonetheless, you can use NSCalendar's components to accomplish this.

let calendar = Calendar.current
let startOfDay1 = calendar.startOfDay(for: date1)
let startOfDay2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([.day], from: startOfDay1, to: startOfDay2)

You can customize that above to get more specific minutes from your date object.

https://developer.apple.com/documentation/foundation/nscalendar/1407925-components

Edit: For Swift 4, you don't need to bridge. You can use Calendar directly (edited code above). https://developer.apple.com/documentation/foundation/calendar/2293176-datecomponents

Derek
  • 1,011
  • 6
  • 17
  • 2
    Why use `NSCalendar`? This is Swift4, you shouldn't be using Foundation data types unless you have a very good reason to do so. You should use `Calendar` rather than `NSCalendar`. – Dávid Pásztor Jan 08 '18 at 21:11
  • Good point @DávidPásztor NSCalendar bridges Calendar which has its own components. – Derek Jan 08 '18 at 21:17
  • If you would like to make calendrical calculations not time sensitive you should use noon instead of midnight. Note that not every day starts at 12:00am http://devstreaming.apple.com/videos/wwdc/2013/227xax5xif2s7s531dsmfs1afo2/227/227.pdf?dl=1 check page 32. You can also watch the video https://developer.apple.com/videos/play/wwdc2013/227/ – Leo Dabus Jan 08 '18 at 21:31
  • @LeoDabus: Doesn't `startOfDay(for:)` take care of that problem? I would expect that it returns the first *valid* date on a day, not necessarily midnight. – Martin R Jan 08 '18 at 21:52
  • Yes but the difference between those dates might be only 23h. Maybe you are right Even between 12pm and 12pm the same issue might occurs – Leo Dabus Jan 08 '18 at 22:02
  • @MartinR It does make a difference https://www.dropbox.com/sh/cdbazcwt2dmxp49/AABsC4bItA4K_KMcQ_Etd3M8a?dl=1 – Leo Dabus Jan 08 '18 at 22:28
  • 1
    @LeoDabus: Your example does not work for me, probably because of the different time zone. But anyway: You are right, it does make a difference, I came to the same conclusion in the meantime. – Martin R Jan 08 '18 at 22:46