Swift - replacement of INT with Date and comparison - ios

I have this code:
let miesiacOd : 2017
let rokOd : Int = 10
let dzienOd : Int = 1
let dataOd = String(format: "%02d-%02d-%02d", rokOd, miesiacOd, dzienOd)
let miesiacDo : Int = 2018
let rokDo : Int = 10
let dzienDo : Int = 1
let dataDo = String(format: "%02d-%02d-%02d", rokDo, miesiacDo, dzienDo)
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd"
I'm trying to compare it, but I have error. When converting variables to dates:
let dataDo2 = dateFormatter2.date(from: dataDo)
let dataOd2 = dateFormatter2.date(from: dataOd)
I have the date and time as a result. For example: 2017-10-01 +000
Why is this happening and how to fix it?
Finally, I would like to check if the current date is within the above dates.
I'm trying to do it like this:
let sprawdzamDostepnoscDat = Date().isBetweeen(date: dataOd2!, andDate: dataDo2!)
extension Date {
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return date1.timeIntervalSince1970 < self.timeIntervalSince1970 && date2.timeIntervalSince1970 > self.timeIntervalSince1970
}
}
Will this solution be ok?

You don't need a formatter (string parser) to create Date:
var dateFromComponents = DateComponents()
dateFromComponents.year = 2017
dateFromComponents.month = 10
dateFromComponents.day = 1
let dateFrom = Calendar.current.date(from: dateFromComponents)
var dateToComponents = DateComponents()
dateToComponents.year = 2018
dateToComponents.month = 10
dateToComponents.day = 1
let dateTo = Calendar.current.date(from: dateToComponents)
Also note that Date is already comparable, therefore your inBetween function can be just:
extension Date {
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return date1 <= self && self <= date2
}
}
However, if you want to ignore time and just compare the days, you should use:
extension Date {
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return Calendar.current.compare(date1, to: self, toGranularity: .day) != .orderedDescending
&& Calendar.current.compare(self, to: date2, toGranularity: .day) != .orderedDescending
}
}

Related

Disabling all other days in calendar view

I have a form in which the user will select days and then select a date from calendar view..
for example: the user will first select sun and mon .. then click on date button an so calendar view will be shown ..
I want the user just be able to select dates in days sun or mon .. i want to disable the other days and highlight them for example ..
what is the best way to do that?
i saw these two libraries:
https://cocoapods.org/pods/JTAppleCalendar
https://github.com/WenchaoD/FSCalendar
but didn't find anything that helps me do what i need using them..
what is the best way to do that?
for JTApplecalendar this is easy
func calendar(_ calendar: JTAppleCalendarView, shouldSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) -> Bool {
return cellState.day == .monday || cellState.day == .sunday
}
Done.
You have to consider Sunday as 1, Monday as 2, Tuesday as 3 and so on Saturday 7.
Define below globally
fileprivate let gregorian: Calendar = Calendar(identifier: .gregorian)
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
var arrDates = NSMutableArray()
Write below line in viewDidLoad.
arrDates = self.getUserSelectedDates([1, 2], calender: self.calendarVW)
Here 1, 2 means user selected Monday and Tuesday (so This array contains only those dates which are Sunday and Monday)
Below is Function that returns Dates array Based on Day value like 1,2 and so on till 7.
func getUserSelectedDates(_ arrWeekDay: [Int], calender calenderVW: FSCalendar?) -> NSMutableArray {
let arrUnAvailibilityDates = NSMutableArray()
let currentDate: Date? = calenderVW?.currentPage
//get calender
let gregorianCalendar = Calendar.init(identifier: .gregorian)
// Start out by getting just the year, month and day components of the current date.
var components: DateComponents? = nil
if let aDate = currentDate {
components = gregorianCalendar.dateComponents([.year, .month, .day, .weekday], from: aDate)
}
// Change the Day component to 1 (for the first day of the month), and zero out the time components.
components?.day = 1
components?.hour = 0
components?.minute = 0
components?.second = 0
//get first day of current month
var firstDateOfCurMonth: Date? = nil
if let aComponents = components {
firstDateOfCurMonth = gregorianCalendar.date(from: aComponents)
}
//create new component to get weekday of first date
var newcomponents: DateComponents? = nil
if let aMonth = firstDateOfCurMonth {
newcomponents = gregorianCalendar.dateComponents([.year, .month, .day, .weekday], from: aMonth)
}
let firstDateWeekDay: Int? = newcomponents?.weekday
//get last month date
let curMonth: Int? = newcomponents?.month
newcomponents?.month = (curMonth ?? 0) + 1
var templastDateOfCurMonth: Date? = nil
if let aNewcomponents = newcomponents {
templastDateOfCurMonth = gregorianCalendar.date(from: aNewcomponents)?.addingTimeInterval(-1)
}
// One second before the start of next month
var lastcomponents: DateComponents? = nil
if let aMonth = templastDateOfCurMonth {
lastcomponents = gregorianCalendar.dateComponents([.year, .month, .day, .weekday], from: aMonth)
}
lastcomponents?.hour = 0
lastcomponents?.minute = 0
lastcomponents?.second = 0
var lastDateOfCurMonth: Date? = nil
if let aLastcomponents = lastcomponents {
lastDateOfCurMonth = gregorianCalendar.date(from: aLastcomponents)
}
var dayDifference = DateComponents()
dayDifference.calendar = gregorianCalendar
if arrWeekDay.count == 0 {
} else if arrWeekDay.count == 1 {
let wantedWeekDay = Int(arrWeekDay[0])
var firstWeekDateOfCurMonth: Date? = nil
if wantedWeekDay == firstDateWeekDay {
firstWeekDateOfCurMonth = firstDateOfCurMonth
} else {
var day: Int = wantedWeekDay - firstDateWeekDay!
if day < 0 {
day += 7
}
day += 1
components?.day = day
firstWeekDateOfCurMonth = gregorianCalendar.date(from: components!)
}
var weekOffset: Int = 0
var nextDate: Date? = firstWeekDateOfCurMonth
repeat {
let strDT: String = getSmallFormatedDate(convertCalendarDate(toNormalDate: nextDate))!
arrUnAvailibilityDates.add(strDT)
weekOffset += 1
dayDifference.weekOfYear = weekOffset
var date: Date? = nil
if let aMonth = firstWeekDateOfCurMonth {
date = gregorianCalendar.date(byAdding: dayDifference, to: aMonth)
}
nextDate = date
} while nextDate?.compare(lastDateOfCurMonth!) == .orderedAscending || nextDate?.compare(lastDateOfCurMonth!) == .orderedSame
}
else {
for i in 0..<arrWeekDay.count {
let wantedWeekDay = Int(arrWeekDay[i])
var firstWeekDateOfCurMonth: Date? = nil
if wantedWeekDay == firstDateWeekDay {
firstWeekDateOfCurMonth = firstDateOfCurMonth
} else {
var day: Int = wantedWeekDay - firstDateWeekDay!
if day < 0 {
day += 7
}
day += 1
components?.day = day
firstWeekDateOfCurMonth = gregorianCalendar.date(from: components!)
}
var weekOffset: Int = 0
var nextDate: Date? = firstWeekDateOfCurMonth
repeat {
let strDT = getSmallFormatedDate(convertCalendarDate(toNormalDate: nextDate))
arrUnAvailibilityDates.add(strDT!)
weekOffset += 1
dayDifference.weekOfYear = weekOffset
var date: Date? = nil
if let aMonth = firstWeekDateOfCurMonth {
date = gregorianCalendar.date(byAdding: dayDifference, to: aMonth)
}
nextDate = date
} while nextDate?.compare(lastDateOfCurMonth!) == .orderedAscending || nextDate?.compare(lastDateOfCurMonth!) == .orderedSame
}
}
return arrUnAvailibilityDates
}
func getSmallFormatedDate(_ localDate: Date?) -> String? {
let dateFormatter = DateFormatter()
let timeZone = NSTimeZone(name: "UTC")
if let aZone = timeZone {
dateFormatter.timeZone = aZone as TimeZone
}
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString: String? = nil
if let aDate = localDate {
dateString = dateFormatter.string(from: aDate)
}
return dateString
}
func convertCalendarDate(toNormalDate selectedDate: Date?) -> Date? {
let sourceTimeZone = NSTimeZone(abbreviation: "UTC")
let destinationTimeZone = NSTimeZone.system as NSTimeZone
var sourceGMTOffset: Int? = nil
if let aDate = selectedDate {
sourceGMTOffset = sourceTimeZone?.secondsFromGMT(for: aDate)
}
var destinationGMTOffset: Int? = nil
if let aDate = selectedDate {
destinationGMTOffset = destinationTimeZone.secondsFromGMT(for: aDate)
}
let interval1 = TimeInterval((destinationGMTOffset ?? 0) - (sourceGMTOffset ?? 0))
var localDate: Date? = nil
if let aDate = selectedDate {
localDate = Date(timeInterval: interval1, since: aDate)
}
return localDate
}
Below is FSCalendar delegates
extension ViewController: FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance {
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
self.view.layoutIfNeeded()
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
}
func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
arrDates = self.getUserSelectedDates([3, 4], calender: self.calendarVW)
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
if arrDates.contains(dateFormatter2.string(from: date)) {
return UIColor.green
} else {
return UIColor.red
}
}
func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
if arrDates.contains(dateFormatter2.string(from: date)) {
return true
}
else {
return false
}
}
}
For function calendar check Saturday or Sunday then it did not select.
The solution for Swift 4.2:
func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
return CheckSatSunday(today: date)
}
// Check Today Is Saturday or Sunday
func CheckSatSunday(today:Date) ->Bool{
var DayExist:Bool
// let today = NSDate()
let calendar =
NSCalendar(calendarIdentifier:NSCalendar.Identifier.gregorian)
let components = calendar!.components([.weekday], from: today)
if components.weekday == 1 {
print("Hello Sunday")
self.showToast(message: "Sunday is Off")
DayExist = false
} else if components.weekday == 7{
print("Hello Saturday")
self.showToast(message: "Saturday is Off")
DayExist = false
} else{
print("It's not Saturday and Sunday ")
DayExist = true
}
print("weekday :\(String(describing: components.weekday)) ")
return DayExist
}

How to get a half of every month from current year in Swift

In my application i have an option to enter the data for every 15days.I have to maintain this for an current year.Please help me to figure out this problem.
For ex: [
"1-1-2018 to 15-1-2018", "16-1-2018 to 31-1-2018",
"1-2-2018 to 15-2-2018", "16-2-2018 to 28-2-2018",
"1-3-2018 to 15-3-2018", "16-3-2018 to 31-3-2018",
"1-4-2018 to 15-4-2018", "16-4-2018 to 30-4-2018",
"1-5-2018 to 15-5-2018", "16-5-2018 to 31-5-2018",
"1-6-2018 to 15-6-2018", "16-6-2018 to 30-6-2018",
"1-7-2018 to 15-7-2018", "16-7-2018 to 31-7-2018",
"1-8-2018 to 15-8-2018", "16-8-2018 to 31-8-2018",
"1-9-2018 to 15-9-2018", "16-9-2018 to 30-9-2018",
"1-10-2018 to 15-10-2018", "16-10-2018 to 31-10-2018",
"1-11-2018 to 15-11-2018", "16-11-2018 to 30-11-2018",
"1-12-2018 to 15-12-2018", "16-12-2018 to 31-12-2018"
]
From Calendar API you can get total number of days for any month in the given date and also first day of the month like below,
extension Calendar {
public func firstDayOfMonth(date: Date) -> Date {
let components = self.dateComponents([.year, .month], from: date)
return self.date(from: components) ?? date
}
public func numberOfDaysInMonthFor(date: Date) -> Int {
let range = self.range(of: .day, in: .month, for: date)
return range?.count ?? 0
}
public func lowerHalfOfMonthFor(date: Date) -> (Date, Date) {
let startDate = self.firstDayOfMonth(date: date)
let endDate = startDate.dateByAppending(day: 14)
return (startDate, endDate)
}
public func upperHalfOfMonthFor(date: Date) -> (Date, Date) {
let firstDayOfMonthDate = self.firstDayOfMonth(date: date)
let totalNoOfDaysInMonth = self.numberOfDaysInMonthFor(date: firstDayOfMonthDate)
let startDate = firstDayOfMonthDate.dateByAppending(day: 15)
let endDate = firstDayOfMonthDate.dateByAppending(day: totalNoOfDaysInMonth - 1)
return (startDate, endDate)
}
}
you can also extend Date to get new date by appending any number of days,
extension Date {
public func dateByAppending(day: Int) -> Date {
let newDate = Calendar.current.date(byAdding: .day, value: day, to: self)
return newDate ?? self
}
public func daysDifference(_ date: Date?) -> Int? {
guard let date = date else { return nil }
return Calendar.current.dateComponents([.day], from: self, to: date).day
}
With the mix of above helper methods, you should be able to achieve the required result like below,
let date = Date()
let lowerHalf = Calendar.current.lowerHalfOfMonthFor(date: date)
let uppperHalf = Calendar.current.upperHalfOfMonthFor(date: date)
Below code will calculate the 15th day if you give the input,
static func getFortnightly(selectedDate : String) -> String?{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yy" //Your date format
if let dateSelected = dateFormatter.date(from: selectedDate) {//according to d
let newDate = Calendar.current.date(byAdding: .weekOfYear, value: 2, to: dateSelected)
let convertedDateToString = dateFormatter.string(from: newDate!)
return convertedDateToString
}
return nil
}
}

Create string array of dates from Dates range

I have Date() properties. startingAt and endingAt. And an array of Date(), which are alreadyRegistred. I have to create an array of strings with dates between startingAt and endingAt. StartingAt and endingAt are included and the last requirement is to exclude alreadyRegistred dates.
Do you have some elegant idea, how to do it? Thanks for help!
Edit: Maximum number of dates in final array will be about 7 days.
Dont forget that a Date is basically just a timestamp, and that you can have access to the addingTimeInterval(_:) method.
Knowing that, is very easy to do some calculation between two dates.
I do not have the whole knowledge about your required business logic, but here is a naive implementation that generates Dates between two dates. I'm sure you can run it in a playground and explore a little bit.
import UIKit
func intervalDates(from startingDate:Date, to endDate:Date, with interval:TimeInterval) -> [Date] {
guard interval > 0 else { return [] }
var dates:[Date] = []
var currentDate = startingDate
while currentDate <= endDate {
currentDate = currentDate.addingTimeInterval(interval)
dates.append(currentDate)
}
return dates
}
let startingDate = Date() // now
let endDate = Date(timeIntervalSinceNow: 3600 * 24 * 7) // one week from now
let intervalBetweenDates:TimeInterval = 3600 * 3// three hours
let dates:[Date] = intervalDates(from: startingDate, to: endDate, with: intervalBetweenDates)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let dateStrings = dates.map{dateFormatter.string(from: $0)}
print("NOW : \(startingDate)")
for (index, string) in dateStrings.enumerated() {
print("\(index) : \(string)")
}
print("END DATE : \(endDate)")
Try this and see:
// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"
// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()
// String date array, to be excluded
let alreadyRegistred = ["01/01/2018", "15/01/2018", "10/02/2018", "20/02/2018", "05/03/2018"]
// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
let stringDate = dateFormatter.string(from: startDate)
startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
if (alreadyRegistred.contains(stringDate)) {
continue
} else {
dateRange.append(stringDate)
}
}
print("Resulting Array - \(dateRange)")
Here is result:
Resulting Array - ["02/01/2018", "03/01/2018", "04/01/2018", "05/01/2018", "06/01/2018", "07/01/2018", "08/01/2018", "09/01/2018", "10/01/2018", "11/01/2018", "12/01/2018", "13/01/2018", "14/01/2018", "16/01/2018", "17/01/2018", "18/01/2018", "19/01/2018", "20/01/2018", "21/01/2018", "22/01/2018", "23/01/2018", "24/01/2018", "25/01/2018", "26/01/2018", "27/01/2018", "28/01/2018", "29/01/2018", "30/01/2018", "31/01/2018", "01/02/2018", "02/02/2018", "03/02/2018", "04/02/2018", "05/02/2018", "06/02/2018", "07/02/2018", "08/02/2018", "09/02/2018", "11/02/2018", "12/02/2018", "13/02/2018", "14/02/2018", "15/02/2018", "16/02/2018", "17/02/2018", "18/02/2018", "19/02/2018", "21/02/2018", "22/02/2018", "23/02/2018", "24/02/2018", "25/02/2018", "26/02/2018", "27/02/2018", "28/02/2018", "01/03/2018", "02/03/2018", "03/03/2018", "04/03/2018", "06/03/2018", "07/03/2018", "08/03/2018"]
let startDate = Date()
let endDate = Date().addingTimeInterval(24*60*60*10) // i did this to get the end date for now
var stringdateArray = [String]()
if let days = getNumberofDays(date1: startDate, date2: endDate) {
for i in 0...days-1 {
let date = startDate.addingTimeInterval(Double(i)*24*3600)
let stringDate = getStringDate(fromDate: date, havingFormat: "yyyy-MM-dd")
if !(alreadyRegisteredArray.contains(stringDate)) { // checking if already registered
stringdateArray.append(stringDate)
}
}
}
and our helper method
let dateFormatter = DateFormatter()
func getStringDate(fromDate: Date,havingFormat: String) -> String {
dateFormatter.dateFormat = havingFormat
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let date = dateFormatter.string(from: fromDate)
return date
}
func getNumberofDays(date1: Date, date2: Date) -> Int? {
let calendar = NSCalendar.current
let date1 = calendar.startOfDay(for: date1)
let date2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([.day], from: date1, to: date2)
return components.day
}

Number of days between two timestamps

I want to get number of days between two timestamps but I am getting wrong value using this code.
Code :
let currentDateTimeStamp = Date().timeIntervalSince1970 * 1000.0
let firstDate = Date.init(timeIntervalSince1970: currentDateTimeStamp)
let lastDate = Date.init(timeIntervalSince1970: individualCellData["joining_date"] as! TimeInterval)
// First Method using extension
let daysBetween = firstDate.interval(ofComponent: .day, fromDate: lastDate)
// Second method
let components = Calendar.current.dateComponents([.day], from: lastDate, to: firstDate)
extension Date {
func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {
let currentCalendar = Calendar.current
guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }
return end - start
}
}
I am getting timestamp from server in milliseconds. What is the correct way ?
let date1 = NSDate(timeIntervalSince1970: 1507211263)//Thursday, 5 October 2017 13:47:43
let date2 = NSDate(timeIntervalSince1970: 1507556863)//Monday, 9 October 2017 13:47:43
var secondsBetween: TimeInterval = date2.timeIntervalSince(date1 as Date)
var numberOfDays = Int(secondsBetween / 86400)
print("There are \(numberOfDays) days in between the two dates.")
//FYI: 86400 seconds = 24 hr
extension Date {
func timeStampToDay(timeStampInMillisecond:Double) -> Int {
let date = Date()
let todaysDateStamp = date.timeIntervalSince1970
let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond / 1000)
var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
return Int(abs(secBetween) / 86400)
}
func timeStampToDay(timeStampInSecond:Double) -> Int {
let date = Date()
let todaysDateStamp = date.timeIntervalSince1970
let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond)
var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
return Int(abs(secBetween) / 86400)
}
}

Swift Problems understanding the result of Calendar.dateComponents

in my app I have a list of contacts including the contacts birthday.
Now I want to see which of my contacts have birthday within in the next 7 days.
I am using a filter on my list to filter and return only thos contacts that match
let timeSpan = 7
let cal = Calendar.current
let now = Date()
var birthDays = contactList.filter { (contact) -> Bool in
if let birthDate = contact.birthDate {
let difference = cal.dateComponents([.day,.year], from: birthDate as Date, to: now! )
print("BD:\(birthDate) : DIFF \(difference.day!)")
return ((difference.day! <= timeSpan) && difference.day! >= 0)
}
return false
}
My hope was so. However the result was weired. So I added that ugly print into my closure in order to see the result of 'difference'
What is odd is that for instance the following:
Today is 2017-08-18 one of my contacts was born on 1987-08-19.
So instead of returning a difference.day of 1 I receive 364. If I swap from: and to: in the dateComponents I receive difference.day of -364.
My expectation was to have a difference.day = 1.
Again in Playground
import UIKit
var now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.date(from: "1987-08-19")
let cal = Calendar.current
let difference = cal.dateComponents([Calendar.Component.day,Calendar.Component.month,Calendar.Component.year], from: s!, to: now )
print("\(difference.day!)") // result is difference.day = 30
What am I doing wrong?
Thanks
You can create an extension to return the number of days from the next birthday as follow:
extension Date {
var year: Int { return Calendar.current.component(.year, from: self) }
var month: Int { return Calendar.current.component(.month, from: self) }
var day: Int { return Calendar.current.component(.day, from: self) }
var noon: Date { return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)! }
var daysFromBirthday: Int {
let nextBirthDate = DateComponents(calendar: .current, year: Date().year + (month < Date().month ? 1 : 0), month: month, day: day, hour: 12).date ?? Date.distantFuture
return Calendar.current.dateComponents([.day], from: Date().noon, to: nextBirthDate).day ?? 0
}
}
And you can now filter your objects as follow:
let timeSpan = 0...7
let birthDays = contactList.filter {
timeSpan ~= $0.birthDate?.daysFromBirthday ?? -1
}
The problem was you were checking the difference of the days from the user's birthday but in the app we will need to get the difference between the current date and the birthday during this year. Say in the example that you have said, it's the difference between 2017-08-19(this year's birthday) and 2017-08-18(current date). You could try the code below.
var now = Date()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.date(from: "1987-08-19")
let cal = Calendar.current
let currentDateComponentsYear = cal.dateComponents([.year,.month,.day], from: newDate!)
var dateComponents = cal.dateComponents([.year,.month,.day], from: s!)
dateComponents.year = currentDateComponentsYear.year
let currentYearBDay = cal.date(from: dateComponents)
currentDateComponentsYear.month
let difference = cal.dateComponents([Calendar.Component.year,Calendar.Component.month,Calendar.Component.day], from:newDate! , to: currentYearBDay! )
let daysDiffernce:Int?
if dateComponents.month == 1 && currentDateComponentsYear.month == 12 && difference.day! < 0 {
let range = cal.range(of: .day, in: .month, for: newDate!)!
let numDays = range.count
daysDiffernce = difference.day! + numDays
} else {
daysDiffernce = difference.day
}
print("\(daysDiffernce!)") //result 1

Resources