Skip to content
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

Check if date or date containing string has 12h (am pm) or 24h format #773

Closed
DimaZava opened this issue Dec 7, 2019 · 3 comments
Closed

Comments

@DimaZava
Copy link
Member

DimaZava commented Dec 7, 2019

I've faced a necessity of checking current device's time display settings, exactly 12/24h format.
What about having such kind of extensions both for Date and String types?

extension Date {

    var is12HourFormat: Bool {
        let dateFormatter = DateFormatter()
        let dateString = dateFormatter.string(from: self)
        return dateString.contains(dateFormatter.amSymbol) || dateString.contains(dateFormatter.pmSymbol)
    }
}
extension String {

    /// Check if string can be formatted as date and if it has 12 hour format.
    /// Returns nil if string isn't a date, and true or false if it has 12 hour format or not.
    var is12HourFormat: Bool? {
        let dateFormatter = DateFormatter()
        let date = dateFormatter.date(from: self)
        return (contains(dateFormatter.amSymbol) || contains(dateFormatter.pmSymbol)) && date != nil
    }
}
@omaralbeik
Copy link
Member

@DimaZava Thanks for bringing this :)
The AM or PM time is coming from the DateFormatter and not from Date, if we have the same date on different devices with different Locale we will get both is12HourFormat and is12HourFormat true for the same date 🤔

@guykogus
Copy link
Contributor

guykogus commented Dec 26, 2019

I think it makes more sense for this to be a Locale extension. Something like

extension Locale {
    var is12HourTimeFormat: Bool {
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .short
        dateFormatter.dateStyle = .none
        dateFormatter.locale = self
        let dateString = dateFormatter.string(from: Date())
        return dateString.contains(dateFormatter.amSymbol) || dateString.contains(dateFormatter.pmSymbol)
    }
}

@DimaZava
Copy link
Member Author

@guykogus I think it's better idea than mine. If you don't mind I can create PR for it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants