当月使用 iOS 的天数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1179945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Number of days in the current month using iOS?
提问by Brock Woolf
How can I get the current number of days in the current month using NSDate or something similar in Cocoa touch?
如何使用 NSDate 或 Cocoa touch 中的类似内容获取当月的当前天数?
回答by Alex Rozanski
You can use the NSDateand NSCalendarclasses:
您可以使用NSDate和NSCalendar类:
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];
todayis an NSDateobject representing the current date; this can be used to work out the number of days in the current month. An NSCalendarobject is then instantiated, which can be used, in conjunction with the NSDatefor the current date, to return the number of days in the current month using the rangeOfUnit:inUnit:forDate:function.
today是一个NSDate表示当前日期的对象;这可用于计算当月的天数。NSCalendar然后实例化一个对象,该对象可以与NSDate当前日期的结合使用,以使用该rangeOfUnit:inUnit:forDate:函数返回当月的天数。
days.lengthwill contain the number of days in the current month.
days.length将包含当月的天数。
Here are the links to the docs for NSDateand NSCalendarif you want more information.
这里是链接到Google文档NSDate和NSCalendar如果您想了解更多信息。
回答by Erez Haim
Swift syntax:
快速语法:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)
回答by Josh Sherick
Swift 3 syntax has changed a bit from Erez's answer:
Swift 3 语法与 Erez 的回答略有不同:
let cal = Calendar(identifier: .gregorian)
let monthRange = cal.range(of: .day, in: .month, for: Date())!
let daysInMonth = monthRange.count
回答by Rob Napier
-[NSCalendar rangeOfUnit:inUnit:forDate:]
-[NSCalendar rangeOfUnit:inUnit:forDate:]

