Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2 dates in weeks and days using swift 3 and xcode 8

I am trying to calculate the difference between 2 dates (one is the current date and the other from datepicker) in weeks and days then displaying the result on a label, that's what i have done so far, i appreciate the help of more experienced developers here!

let EDD = datePicker.date let now = NSDate()  let formatter = DateComponentsFormatter() formatter.unitsStyle = .short formatter.allowedUnits = [.day] formatter.maximumUnitCount = 2     let string = formatter.string (from: now as Date, to: EDD)  label.text = string 
like image 211
FormulaOne Avatar asked Feb 17 '17 09:02

FormulaOne


People also ask

How do I get the difference between two dates in Swift?

Date Difference Extension in Swiftlet formatter = DateFormatter() formatter. dateFormat = "yyyy/MM/dd HH:mm" let xmas = formatter. date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear!

How do you calculate the difference in weeks between two dates?

To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week. How many days are between two dates?

Can you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.

How can I tell the difference between two days?

To calculate the number of days between two dates, you need to subtract the start date from the end date.


1 Answers

You can use Calendar's dateComponents(_:from:to:) to find the difference between 2 dates to your desired units.

Example:

let dateRangeStart = Date() let dateRangeEnd = Date().addingTimeInterval(12345678) let components = Calendar.current.dateComponents([.weekOfYear, .month], from: dateRangeStart, to: dateRangeEnd)  print(dateRangeStart) print(dateRangeEnd) print("difference is \(components.month ?? 0) months and \(components.weekOfYear ?? 0) weeks")   > 2017-02-17 10:05:19 +0000 > 2017-07-10 07:26:37 +0000 > difference is 4 months and 3 weeks  let months = components.month ?? 0 let weeks = components.weekOfYear ?? 0 
like image 99
Ashley Mills Avatar answered Sep 30 '22 01:09

Ashley Mills