Skip to content

Allow whitespaces after parsed content in DateFormatter.date(from:) #2785

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

Merged
merged 1 commit into from
May 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions Sources/Foundation/DateFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,15 @@ open class DateFormatter : Formatter {
}

// range.length is updated with the last position of the input string that was parsed
guard range.length == string.length else {
// The whole string was not parsed
guard let swiftRange = Range(NSRange(range), in: string) else {
fatalError("Incorrect range \(range) in \(string)")
}

// Apple DateFormatter implementation returns nil
// if non-whitespace sharacters are left after parsed content.
let remainder = String(string[swiftRange.upperBound...])
let characterSet = CharacterSet(charactersIn: remainder)
guard CharacterSet.whitespaces.isSuperset(of: characterSet) else {
return nil
}
return date
Expand Down
9 changes: 9 additions & 0 deletions Tests/Foundation/Tests/TestDateFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,15 @@ class TestDateFormatter: XCTestCase {
let d1 = try XCTUnwrap(formatter.date(from: "2018-03-09"))
XCTAssertEqual(d1.description, "2018-03-09 00:00:00 +0000")

// DateFormatter should allow any kind of whitespace before and after parsed content
let whitespaces = " \t\u{00a0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200a}\u{202f}\u{205f}\u{3000}"
let d1Prefix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09"))
XCTAssertEqual(d1.description, d1Prefix.description)
let d1PrefixSuffix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09\(whitespaces)"))
XCTAssertEqual(d1.description, d1PrefixSuffix.description)
let d1Suffix = try XCTUnwrap(formatter.date(from: "2018-03-09\(whitespaces)"))
XCTAssertEqual(d1.description, d1Suffix.description)

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
XCTAssertNil(formatter.date(from: "2018-03-09"))
let d2 = try XCTUnwrap(formatter.date(from: "2018-03-09T10:25:16+01:00"))
Expand Down