Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DateInRegionFormatter crashes with any non-default allowed components #371

Closed
andriichernenko opened this issue Jan 6, 2017 · 1 comment
Assignees
Labels
Milestone

Comments

@andriichernenko
Copy link

andriichernenko commented Jan 6, 2017

The following code crashes with 4.0.10:

let from = DateInRegion() + 2.days
let to = DateInRegion()

let fmt = DateInRegionFormatter()
fmt.allowedComponents = [.day]

try fmt.colloquial(from: from, to: to).colloquial // crash here

The problem seems to be here:

public class DateInRegionFormatter {
    // ...
    public func colloquial(from fDate: DateInRegion, to tDate: DateInRegion) throws -> (colloquial: String, time: String?) {
	guard fDate.region.calendar == tDate.region.calendar else {
		throw DateError.DifferentCalendar
	}
	let cal = fDate.region.calendar
	let cmp = cal.dateComponents(self.allowedComponents, from: fDate.absoluteDate, to: tDate.absoluteDate)
	let isFuture = (fDate > tDate)
	
	if cmp.year != 0 { // this condition is true when cmp.year is nil
		// force unwrapping cmp.year results in crash 
		let colloquial_time = try self.colloquial_time(forUnit: .year, withValue: cmp.year!, date: fDate)
		// ...
	}
	// ...
malcommac added a commit that referenced this issue Jan 8, 2017
Fixed issue #371 where nil optional value is unwrapped when a time component is evaluated but it not part of the formatter's set .allowedComponents.
@malcommac
Copy link
Owner

malcommac commented Jan 8, 2017

Thank you for your report; it's a bug because it try to unwrap and verify a component that is not part of the allowedComponents property.
I've just fixed it in this commit 94682db.
It will be part of the 4.0.11 release.

Just a note:
When you do let from = DateInRegion() + 2.days you are adding 2 days to the current date+time, so unless the current datetime is midnight resulting colloquial string is like "tomorrow" (or yesterday, the difference is less than 1 day).

@malcommac malcommac added the bug label Jan 8, 2017
@malcommac malcommac added this to the 4.0.0 milestone Jan 8, 2017
@malcommac malcommac self-assigned this Jan 8, 2017
@malcommac malcommac modified the milestones: 4.0.11, 4.0.0 Jan 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants