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
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!
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?
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.
To calculate the number of days between two dates, you need to subtract the start date from the end date.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With