I am trying to check if a particular day exists in a month or not. However unable to find anything of help. To give an example I tried below code in Playground;
var components = DateComponents()
components.month = 2
components.year = 2016
components.day = 30
components.calendar = Calendar.current
components.date
This gives the answer;
"Mar 1, 2016, 12:00 AM"
So what it does is it tries to manipulate with TimeZones and moves the needle. Hence I'm unable to find a way to check if a particular day exists in a given month & year.
Can anyone please guide.
DateComponents
has an isValidDate
property, which you can use
for that purpose:
var components = DateComponents()
components.month = 2
components.year = 2016
components.day = 30
components.calendar = Calendar.current
print(components.isValidDate) // false
Lets break this down to -
How to check number of days in a month-year?
Then your problem boils down to check if the given day is within the range [1, numDaysInMonthYear).
The code for above is this:
// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)
let numDaysInMonthYear = range.length
print(numDaysInMonthYear) // 31
Credits: How do I find the number of days in given month and year using swift
try this below method you can check the particular day exists in a month.
function checkDayIsExist(year:Int,month:Int,day:Int) -> Bool {
let dateComponents = DateComponents(year: year, month: month)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
let numberOfDays = calendar.range(of: .day, in: .month, for: date)!
return numberOfDays.count >= day
}
Call by
print(checkDayIsExist(year:2017,month:7,day:31)) // true
You can check by using NSDateFormatter / DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
let dateString = "30 02 2017"
if let date = dateFormatter.date(from: dateString)
{
print("Date \(date)")
}
else
{
print("Date not existed")
}
You can change the date formatter's dateFormate based on your input string.