Number of days in the current month using iOS?

半腔热情 提交于 2019-11-27 04:21:33

问题


How can I get the current number of days in the current month using NSDate or something similar in Cocoa touch?


回答1:


You can use the NSDate and NSCalendar classes:

NSDate *today = [NSDate date]; //Get a date object for today's date
NSCalendar *c = [NSCalendar currentCalendar];
NSRange days = [c rangeOfUnit:NSDayCalendarUnit 
                       inUnit:NSMonthCalendarUnit 
                      forDate:today];

today is an NSDate object representing the current date; this can be used to work out the number of days in the current month. An NSCalendar object is then instantiated, which can be used, in conjunction with the NSDate for the current date, to return the number of days in the current month using the rangeOfUnit:inUnit:forDate: function.

days.length will contain the number of days in the current month.

Here are the links to the docs for NSDate and NSCalendar if you want more information.




回答2:


Swift syntax:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)



回答3:


-[NSCalendar rangeOfUnit:inUnit:forDate:]




回答4:


Swift 3 syntax has changed a bit from Erez's answer:

let cal = Calendar(identifier: .gregorian)
let monthRange = cal.range(of: .day, in: .month, for: Date())!
let daysInMonth = monthRange.count


来源:https://stackoverflow.com/questions/1179945/number-of-days-in-the-current-month-using-ios

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