Skip to content

Commit

Permalink
Fix Date to timeString conversion (#306)
Browse files Browse the repository at this point in the history
* Add date format with AM/PM

* Set locale
  • Loading branch information
kvld authored Jun 27, 2018
1 parent e17b0f7 commit 39e4446
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
19 changes: 14 additions & 5 deletions Stepic/NSDateExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,21 @@ extension Date {
extension TimeInterval {
init(timeString: String) {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if (formatter.date(from: timeString)?.timeIntervalSince1970) == nil {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = TimeZone(abbreviation: "UTC")!
formatter.locale = Locale(identifier: "en_US_POSIX")

let dateFormats = ["yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'hh:mm:ss.SSS a'Z'"]

for dateFormat in dateFormats {
formatter.dateFormat = dateFormat
if let timeInterval = formatter.date(from: timeString)?.timeIntervalSince1970 {
self = timeInterval
return
}
}

self = formatter.date(from: timeString)!.timeIntervalSince1970
}
}
1 change: 1 addition & 0 deletions Stepic/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class Parser: NSObject {
func timedateStringFromDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return dateFormatter.string(from: date)
}
Expand Down

0 comments on commit 39e4446

Please sign in to comment.