我使用此代码获取当周的天数:
static func currentDayOfWeek() -> Int {
let comp = NSCalendar.current.dateComponents([.weekday], from: Date())
if comp.weekday == 1 {
return 7
}
return comp.weekday! - 1
}
Monday = 1
Tuesday = 2
...........
Sunday = 7
我无法弄清楚如何获得当月的当月数字。
例如,今天当天的当月数字应为3
,而今年的数字应为277
。
有什么建议吗?
答案 0 :(得分:6)
let dayYear = Calendar.current.ordinality(of: .day, in: .year, for: Date())
let dayMonth = Calendar.current.ordinality(of: .day, in: .month, for: Date())
答案 1 :(得分:1)
func currentDayOfMonth()->Int {
return NSCalendar.currentCalendar().ordinalityOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: NSDate())
}
func currentDayOfYear()->Int {
return NSCalendar.currentCalendar().ordinalityOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Year, forDate: NSDate())
}
答案 2 :(得分:-1)
原始答案来自this帖子。
这将返回"星期一"或者星期几:
func getDayOfWeek(_ today:String) -> String? {
let weekdays = [1:"Sunday", 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"Thursday", 6:"Friday", 7:"Saturday"]
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
if let todayDate = formatter.date(from: today) {
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
let day = weekdays[weekDay]
return day
} else {
return nil
}
}
getDayOfWeek("10-03-2016")
这将返回" 1"或者一周中的一天的数字:
func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
if let todayDate = formatter.date(from: today) {
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
} else {
return nil
}
}
getDayOfWeek("10-03-2016")