I have the following code:
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
}
The date in getWeek(addDays(Date, amount: 6))
returns dec 27, 2015, 7:16PM
This is correct ( next sunday) However if i try to return the week number for that date, it returns 1
whereas this should be 53. How can i get the correct week number?
According to Apple Developer Technical Support:
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.
With that change getWeek()
starts producing results that match ISO 8601. Specifically:
print(self.getWeek(self.dateFromFixedFormatString("2015-12-27 12:34")))
print(self.getWeek(self.dateFromFixedFormatString("2015-12-28 12:34")))
Prints:
Assuming:
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
}
So anyone stating the GregorianCalendar does not work in my code is correct, and should be using the NSCalendarIdentifierISO8601 specifically. NSCalendar.currentCalendar()
does not automatically get the ISO calendar. (very strange)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With