0

i am completely new in iPhone app development. i am trying to find difference between min_date and max_date in hours. and wants save its value in textfield. Kindly Provide me complete code to find out difference between both of dates. e.g. if min_date: 12/07/1989, 12:00 am and max_date: 13/07/1989,12:00 am , then total hours will be 24 hours. Please provide me code in swift 3.0.

Ruchi
  • 13
  • 1
  • 5
  • Possible duplicate of [Getting the difference between two NSDates in (months/days/hours/minutes/seconds)](https://stackoverflow.com/questions/27182023/getting-the-difference-between-two-nsdates-in-months-days-hours-minutes-seconds) – Kiran Sarvaiya Nov 07 '17 at 07:30

3 Answers3

1

First, use timeIntervalSince to get the difference in seconds:

 let timeInterval = max_date.timeIntervalSince(min_date)

Then you can do some maths to calculate the number of hours

let hours = timeInterval / 60 / 60

You can choose to floor or ceiling this number, depending on your requirements.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I am founding this error Value of type 'String' has no member 'timeIntervalSince' . (i am taking a string in var max_date and var min_ date. then max_date= dateFormatter.string(from: datePicker.date) print("FromDate: \(max_date)") similarly min_date. and on a button click i am coding like dis let timeInterval = max_date.timeIntervalSince(min_date) let hours = timeInterval / 60 / 60) – Ruchi Nov 07 '17 at 08:38
  • @Ruchi right, so you are working with strings. Look up how to convert string to date. – Sweeper Nov 07 '17 at 08:39
  • @Ruchi if you think my answer answers your question, please consider accepting it by clicking on that checkmark! – Sweeper Nov 07 '17 at 22:28
0
let previousDate = ...
let now = Date()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2   // often, you don't care about seconds 
if the elapsed time is in months, so you'll set max unit to whatever is 
appropriate in your case

let string = formatter.string(from: previousDate, to: now)
Muhammad Shauket
  • 2,643
  • 19
  • 40
0
let minDate = Date() // your min date

let maxDate = Date() // your max date

let components = Calendar.current.dateComponents([.hour], from: minDate, to: maxDate) 

It's the most flexible method for search difference between two dates. You can use other components to search for months, days, years etc.