Question: Infinite loop on Calendar.current.date(bySetting:value:of:)

Question

Infinite loop on Calendar.current.date(bySetting:value:of:)

Answers 0
Added at 2017-11-08 16:11
Tags
Question

I just ran into something strange with the Calendar API when trying to get the first day of a particular month.

import Foundation

//2017-12-01 23:00:00 +0000
let date = Date(timeIntervalSinceReferenceDate: 533862000.0)

let secondDate = Calendar.current.date(bySetting: .day, value: 2, of: date)
let thirdDate = Calendar.current.date(bySetting: .day, value: 1, of: date)

print("Passed")

In a Swift 4 Playground, the property observer on the right displays values for date and secondDate, but enters in an infinite loop when evaluating the let thirdDate = ... expression.

Activity Indicator reports of 99% CPU usage and RAM usage increases at around +100MB/second, and so does the Debug Navigator in XCode when ran inside an iOS project (until the app is killed at around 1.3GB RAM usage)

This is not happening for all dates, but is consistent with this particular date.

I've gone through the docs of Calendar but I can't figure out why this happens.

I came up with a workaround like this :

let date = Calendar.current.startOfDay(for: someDate)
var dc = Calendar.current.dateComponents([.month, .year, .day], from: date)
dc.day = 1
let firstDayOfMonth = Calendar.current.date(from: dc)

But I'd very much like to get an explanation as to why Calendar.current.date(bySetting: .day, value: 1, of: date) is failing that hard. Is there something I missed here?

Edit: it happens for the timezone GMT+2, but doesn't anymore if I change my system settings to GMT+1.

Answers to

Infinite loop on Calendar.current.date(bySetting:value:of:)

Source Show
◀ Wstecz