Skip to content
Open
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
32 changes: 30 additions & 2 deletions Sources/iCalendarParser/Models/DateTimeType.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import Foundation


extension Locale {
static func is12HoursFormat() -> Bool {
DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)?.range(of: "a") != nil
}

static func is24HoursFormat() -> Bool {
!Self.is12HoursFormat()
}

func is12HoursFormat() -> Bool {
DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: self)?.range(of: "a") != nil
}

func is24HoursFormat() -> Bool {
!is12HoursFormat()
}
}

public enum DateTimeType {
case date
case dateTime
Expand All @@ -17,7 +36,8 @@ public enum DateTimeType {
} else {
formatter.timeZone = TimeZone(abbreviation: "UTC")
}



formatter.dateFormat = {
switch self {
case .date:
Expand All @@ -28,7 +48,15 @@ public enum DateTimeType {
: "yyyyMMdd'T'HHmmss"
}
}()


formatter.locale = {
if Locale.is12HoursFormat() {
return Locale(identifier: "en_US_POSIX")
} else {
return Locale.current
}
}()

return formatter
}
}
14 changes: 14 additions & 0 deletions Tests/iCalendarParserTests/DateTimeTypeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,18 @@ final class DateTimeTypeTests: XCTestCase {
let wrongDate = dateTime.type.dateFormatter().date(from: "19700327T020000")
XCTAssertNotEqual(dateTime.date, wrongDate)
}

func testCorrectHourCycle() {
// to test this toggle off/on 24-hour time in settings
let property = ICProperty("DTSTART", "19700329T020000")
let dateTime = PropertyBuilder.buildDateTime(from: property)!
let dateFormatter = dateTime.type.dateFormatter()
let currentLocale = Locale.current
if (currentLocale.is12HoursFormat()){
XCTAssert(dateFormatter.locale.hourCycle == .oneToTwelve)
}
else {
XCTAssert(dateFormatter.locale.hourCycle == .zeroToTwentyThree)
}
}
}