加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – NSDate返回错误的周数

发布时间:2020-12-14 04:45:59 所属栏目:百科 来源:网络整理
导读:我有以下代码: getWeek(addDays(Date,amount: 6))func addDays(date: NSDate,amount: Int) - NSDate { // calculation $additionalDays let additionalDays = amount // adding $additionalDays let components = NSDateComponents() components.day = addi
我有以下代码:

getWeek(addDays(Date,amount: 6))

func addDays(date: NSDate,amount: Int) -> NSDate {
    // calculation $additionalDays
    let additionalDays = amount
    // adding $additionalDays
    let components = NSDateComponents()
    components.day = additionalDays

    // important: NSCalendarOptions(0)
     let futureDate = NSCalendar.currentCalendar()
    .dateByAddingComponents(components,toDate: date,options: NSCalendarOptions(rawValue: 0))
    return futureDate!
}

func getWeek(today:NSDate)->Int? {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.WeekOfYear,fromDate: today)
    let weekNumber = myComponents.weekOfYear
   return weekNumber
}

getWeek中的日期(addDays(日期,金额:6))返回2015年12月27日,下午7:16
这是正确的(下周日)然而,如果我尝试返回该日期的周数,它将返回1,而这应该是53.我怎样才能获得正确的周数?

解决方法

根据Apple开发者技术支持:

27 Dec 2015 is week 52,not week 53. The first day of week 53 in 2015 is 28 Dec.

Regardless,you’re correct that the value returned by your getWeek() function does not match ISO 8601. The reason for that is that you’re using NSCalendarIdentifierGregorian rather than NSCalendarIdentifierISO8601. There are /lots/ of different ways to do week-of-year calculations. I can go into the gory details if you’d like,but the ‘take home’ message here is that,if you want ISO 8601 week calculations,you should use NSCalendarIdentifierISO8601.

通过该更改,getWeek()开始生成与ISO 8601匹配的结果.具体来说:

print(self.getWeek(self.dateFromFixedFormatString("2015-12-27 12:34")))
print(self.getWeek(self.dateFromFixedFormatString("2015-12-28 12:34")))

打印:

> 52
> 53

假设:

func dateFromFixedFormatString(dateStr: String) -> NSDate {
   let df = NSDateFormatter()
   df.locale = NSLocale(localeIdentifier: "en_US_POSIX")
   df.dateFormat = "yyyy-MM-dd HH:mm"
   return df.dateFromString(dateStr)!
}
func getWeek(today:NSDate) -> Int {
   let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
   let myComponents = myCalendar.components(.WeekOfYear,fromDate: today)
   let weekNumber = myComponents.weekOfYear
   return weekNumber
}

因此任何说明GregorianCalendar在我的代码中不起作用的人都是正确的,并且应该特别使用NSCalendarIdentifierISO8601. NSCalendar.currentCalendar()不会自动获取ISO日历. (很奇怪)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读