Skip to content

Instantly share code, notes, and snippets.

@rl-pavel
Last active February 1, 2023 03:17
Show Gist options
  • Save rl-pavel/68a53147363a417995b04f2ecab041e1 to your computer and use it in GitHub Desktop.
Save rl-pavel/68a53147363a417995b04f2ecab041e1 to your computer and use it in GitHub Desktop.
Localized Date Formatting
// US locale:
// Oct 14, 2020, 7:50 PM
Date().format(with: [.monthShort, .dayOfMonth, .yearFull, .hour, .minute], locale: Locale(identifier: "en_US"))!
// French locale:
// 14 Oct 2020 à 19:50
Date().format(with: [.monthShort, .dayOfMonth, .yearFull, .hour, .minute], locale: Locale(identifier: "fr"))!
import Foundation
extension Date {
// MARK: - Helper types
enum DateFormatComponents: String {
/// 1997
case yearFull = "yyyy"
/// 97 (1997)
case yearShort = "yy"
/// 7
case monthDigit = "M"
/// 07
case monthDigitPadded = "MM"
/// Jul
case monthShort = "MMM"
/// July
case monthFull = "MMMM"
/// J (July)
case monthLetter = "MMMMM"
/// 5
case dayOfMonth = "d"
/// Sat
case weekdayShort = "EEE"
/// Saturday
case weekdayFull = "EEEE"
/// S (Saturday)
case weekdayLetter = "EEEEE"
/// Localized **13** or **1 PM**, depending on the locale.
case hour = "j"
/// 20
case minute = "m"
/// 08
case second = "ss"
/// CST
case timeZone = "zzz"
/// **Central Standard Time** or **CST-06:00** or if full name is unavailable.
case timeZoneFull = "zzzz"
}
// MARK: - Date Math
func advance(_ component: Calendar.Component, by value: Int, calendar: Calendar = Calendar.current) -> Date? {
return calendar.date(byAdding: component, value: value, to: self)
}
func isSame(_ granularity: Calendar.Component, as other: Date, calendar: Calendar = Calendar.current) -> Bool {
return calendar.compare(self, to: other, toGranularity: granularity) == .orderedSame
}
// MARK: - Date Formatting
func format(
with components: [DateFormatComponents],
in timeZone: TimeZone? = .current,
using dateFormatter: DateFormatter = DateFormatter(),
locale: Locale = .current) -> String? {
let template = components.map(\.rawValue).joined(separator: " ")
guard let localizedFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: locale) else {
return nil
}
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = localizedFormat
return dateFormatter.string(from: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment