Skip to content

Commit ab75dee

Browse files
authored
Merge pull request #2785 from readdle/date-formatter-whitespaces
Allow whitespaces after parsed content in DateFormatter.date(from:)
2 parents 117dfd4 + dd22d7d commit ab75dee

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

Sources/Foundation/DateFormatter.swift

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,15 @@ open class DateFormatter : Formatter {
6464
}
6565

6666
// range.length is updated with the last position of the input string that was parsed
67-
guard range.length == string.length else {
68-
// The whole string was not parsed
67+
guard let swiftRange = Range(NSRange(range), in: string) else {
68+
fatalError("Incorrect range \(range) in \(string)")
69+
}
70+
71+
// Apple DateFormatter implementation returns nil
72+
// if non-whitespace sharacters are left after parsed content.
73+
let remainder = String(string[swiftRange.upperBound...])
74+
let characterSet = CharacterSet(charactersIn: remainder)
75+
guard CharacterSet.whitespaces.isSuperset(of: characterSet) else {
6976
return nil
7077
}
7178
return date

Tests/Foundation/Tests/TestDateFormatter.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,15 @@ class TestDateFormatter: XCTestCase {
419419
let d1 = try XCTUnwrap(formatter.date(from: "2018-03-09"))
420420
XCTAssertEqual(d1.description, "2018-03-09 00:00:00 +0000")
421421

422+
// DateFormatter should allow any kind of whitespace before and after parsed content
423+
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}"
424+
let d1Prefix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09"))
425+
XCTAssertEqual(d1.description, d1Prefix.description)
426+
let d1PrefixSuffix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09\(whitespaces)"))
427+
XCTAssertEqual(d1.description, d1PrefixSuffix.description)
428+
let d1Suffix = try XCTUnwrap(formatter.date(from: "2018-03-09\(whitespaces)"))
429+
XCTAssertEqual(d1.description, d1Suffix.description)
430+
422431
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
423432
XCTAssertNil(formatter.date(from: "2018-03-09"))
424433
let d2 = try XCTUnwrap(formatter.date(from: "2018-03-09T10:25:16+01:00"))

0 commit comments

Comments
 (0)