Skip to content

Commit

Permalink
Fix the 12 hour format based on current Locale (#96)
Browse files Browse the repository at this point in the history
* use ISO8601DateFormatter to avoid locale problems on ISO formats

* fix min API

* comment the formatIsoDate

Co-authored-by: Lucas Paim <[email protected]>
  • Loading branch information
lucasmpaim and Lucas Paim authored Oct 1, 2020
1 parent 0a8461f commit e21c88a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
7 changes: 7 additions & 0 deletions .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 36 additions & 1 deletion Sources/DateHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,50 @@ public extension Date {

/// Converts the date to string based on a date format, optional timezone and optional locale.
func toString(format: DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Locale.current) -> String {
var useLocale = locale

switch format {
case .dotNet:
let offset = Foundation.NSTimeZone.default.secondsFromGMT() / 3600
let nowMillis = 1000 * self.timeIntervalSince1970
return String(format: format.stringFormat, nowMillis, offset)
case .isoDateTimeMilliSec, .isoDateTimeSec, .isoDateTime,
.isoYear,. isoDate, .isoYearMonth:
if #available(iOS 11.0, watchOS 3, tvOS 10, macOS 13, *) {
return formatIsoDate(format: format, timeZone: timeZone)
} else {
useLocale = Locale(identifier: "en_US_POSIX")
}
default:
break
}
let formatter = Date.cachedDateFormatters.cachedFormatter(format.stringFormat, timeZone: timeZone.timeZone, locale: locale)
let formatter = Date.cachedDateFormatters.cachedFormatter(format.stringFormat, timeZone: timeZone.timeZone, locale: useLocale)
return formatter.string(from: self)
}

/// Converts to ISO format using the new API
@available(iOS 11.0, watchOS 3, tvOS 10, macOS 13, *)
func formatIsoDate(format: DateFormatType, timeZone: TimeZoneType = .local) -> String {
let formatter = ISO8601DateFormatter()
formatter.timeZone = timeZone.timeZone

var options: ISO8601DateFormatter.Options = []
switch format {
case .isoDate:
options = [.withFullDate]
case .isoYearMonth:
options = [.withYear, .withMonth]
case .isoYear:
options = [.withYear]
case .isoDateTimeSec, .isoDateTime:
options = [.withInternetDateTime]
case .isoDateTimeMilliSec:
options = [.withInternetDateTime, .withFractionalSeconds]
default:
fatalError("Unimplemented format \(format)")
}

formatter.formatOptions = options
return formatter.string(from: self)
}

Expand Down

0 comments on commit e21c88a

Please sign in to comment.