Get total include months between 2 date in swift

无人久伴 提交于 2021-02-16 20:54:31

问题


how to get a total month between 2 dates? here is the normal way to get a date

1) startDate: 2020-2-22 10:25:00

2) endDate: 2020-3-3 12:34:00

let diffInDate:Int = Calendar.current.dateComponents([.month], from: startDate, to: endDate).month!

if we check as per the above-given date it will return 0 due to not total 30 days.

now I want the result with a month difference if we check the above date it should return 1 because the month changes. so is there any way to check date difference including that month?


回答1:


As you have correctly identified dateComponents(_:from:to:) doesn't count the fractional months.

However, there is another overload, that computes the difference between DateComponents instead of Dates. We can strip off everything we don't need (day, hour, minute etc) from the start and end Dates, pass them into this overload, and it should do the calculation for us. This is analogous to rounding floating point numbers before subtracting them, so that you can get the difference between their integer parts.

let startDateComponents = Calendar.current.dateComponents([.year, .month], from: startDate)
let endDateComponents = Calendar.current.dateComponents([.year, .month], from: endDate)
let diffInDate = Calendar.current.dateComponents([.month], from: startDateComponents, to: endDateComponents).month!

Notice that we get the year component of the start and end dates as well, because the year is needed in the calculation as well. But when we calculate the difference, we only want the month.




回答2:


Get the month component from startDate and endDate and then calculate the difference between them, i.e.

let startMonth = Calendar.current.component(.month, from: startDate)
let endMonth = Calendar.current.component(.month, from: endDate)
let difference = abs(endMonth - startMonth) //1



回答3:


I would point out that the question should be edited to indicate that you wished to know how to list out the months, since the calculation of an integer denoting the inclusive number of months between 2 dates may be a completely different task. And for that, sweeper's answer should already be considered more than adequate.

I will attempt to give a solution in response to the comment where you clarify that you want a list of the months.

import UIKit

func makeDate(year: Int, month: Int, day: Int) -> Date {
    let calendar = Calendar(identifier: .gregorian)
    let components = DateComponents(year: year, month: month, day: day) //, hour: hr, minute: min, second: sec)
    return calendar.date(from: components)!
}

let date1 = makeDate(year: 2016, month: 10, day: 23) // 23 OCT 2016
let date2 = makeDate(year: 2020, month: 7, day: 10) // 10 JULY 2020

func printMonths(date1: Date, date2: Date) {

    guard date1 < date2 else {return}

    let month1 = Calendar.current.component(.month, from: date1)
    let month2 = Calendar.current.component(.month, from: date2)
    let year1 = Calendar.current.component(.year, from: date1)
    let year2 = Calendar.current.component(.year, from: date2)

    if year1 == year2 {
        for month in month1...month2 {
            print(DateFormatter().monthSymbols[month - 1])
        }
    } else {
        for year in year1...year2 {
            print(year)
            switch year {
            case year1:
                for month in month1...12 {
                    print("   \(DateFormatter().monthSymbols[month - 1])")
                }
            case year2:
                for month in 1...month2 {
                    print("   \(DateFormatter().monthSymbols[month - 1])")
                }
            default:
                for month in 1...12 {
                    print("   \(DateFormatter().monthSymbols[month - 1])")
                }
            }
            print()
        }
    }
}

printMonths(date1: date1, date2: date2)

This function will print out the month names in order from date1 to date2, printing the years for the months if the 2 dates have different years.

It can easily be modified to print the total number of months by just using a counter each time a month name is printed out, if you wanted that too.

Output from example dates:

2016
   October
   November
   December

2017
   January
   February
   March
   April
   May
   June
   July
   August
   September
   October
   November
   December

2018
   January
   February
   March
   April
   May
   June
   July
   August
   September
   October
   November
   December

2019
   January
   February
   March
   April
   May
   June
   July
   August
   September
   October
   November
   December

2020
   January
   February
   March
   April
   May
   June
   July


来源:https://stackoverflow.com/questions/60500764/get-total-include-months-between-2-date-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!