Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting incorrect start and end dates from weekOfYear

Tags:

date

ios

swift

When I run this code:

let calendar = Calendar.current
    var dateComponents = DateComponents()
    dateComponents.weekday = calendar.firstWeekday
    dateComponents.weekOfYear = 2
    dateComponents.year = 2017
    let startOfWeek = calendar.date(from: dateComponents)
    let endOfWeek = calendar.date(byAdding: .day, value: 6, to: startOfWeek!)
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    print(formatter.string(from: startOfWeek!))
    print(formatter.string(from: endOfWeek!))

It prints this:

1/8/17
    1/14/17

When I change the code to this:

dateComponents.weekOfYear = 1
    dateComponents.year = 2017

It prints this:

12/31/17
    1/6/18

Why is it 12/31/17?

like image 474
7owen Avatar asked Dec 09 '16 07:12

7owen


1 Answers

When I use .full style to print the dates, I get Sunday, December 31, 2017 for the first date, but it's obviously wrong because December 31 is a Thursday.

If you want to get the correct date, use yearForWeekOfYear instead of year. Docs:

You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example, the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar.

Alternative, you can be a little naughty and not listen to the docs and use weekOfYear = 54:

let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.weekday = calendar.firstWeekday
dateComponents.weekOfYear = 54
dateComponents.year = 2017
let startOfWeek = calendar.date(from: dateComponents)
let endOfWeek = calendar.date(byAdding: .day, value: 6, to: startOfWeek!)
let formatter = DateFormatter()
formatter.dateStyle = .short
print(formatter.string(from: startOfWeek!))
print(formatter.string(from: endOfWeek!))

This prints:

1/1/17
1/7/17

which is coincidentally, the correct dates.

like image 94
Sweeper Avatar answered Nov 16 '22 21:11

Sweeper