Search code examples
iosswiftcalendarnsdatensdatecomponents

Given year & month, how to check a particular day exists in that month


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.


Solution

  • 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