Skip to content

Instantly share code, notes, and snippets.

@rbresjer
Created December 30, 2016 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbresjer/1f1488693491ed778d0a4e863559d6ba to your computer and use it in GitHub Desktop.
Save rbresjer/1f1488693491ed778d0a4e863559d6ba to your computer and use it in GitHub Desktop.
Example of Swift date manager which can convert dates to strings and vice versa, with auto detection of date formats
//
// DateManager.swift
//
// Created by Rutger Bresjer on 30/12/2016.
// Copyright © 2016 Woost. All rights reserved.
//
import Foundation
class DateManager {
static let shared = DateManager()
private init() {}
private let defaultDateFormat = "EEEE dd MMMM yyyy"
private lazy var dateFormatter: DateFormatter = {
let _dateFormatter = DateFormatter()
_dateFormatter.locale = Bundle.main.preferredLocalizations.first.flatMap(Locale.init) ?? Locale.current
return _dateFormatter
}()
func string(from date: Date, format: String? = nil) -> String {
dateFormatter.dateFormat = format ?? defaultDateFormat
return dateFormatter.string(from: date)
}
func date(from string: String, format: String? = nil) -> Date? {
guard let dateFormat = format ?? dateFormat(for: string) else { return nil }
dateFormatter.dateFormat = dateFormat
return dateFormatter.date(from: string)
}
private func dateFormat(for string: String) -> String? {
let dateFormats = [
(dateFormat: "yyyyMMdd",
regex: "^(19|20)\\d\\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$"),
(dateFormat: "yyyy-MM-dd",
regex: "^(19|20)\\d\\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$"),
(dateFormat: "yyyy-MM-dd HH:mm:ss",
regex: "^(19|20)\\d\\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$"),
(dateFormat: "yyyyMMddHHmmss",
regex: "^(19|20)\\d\\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])$")
]
return dateFormats
.filter { string.range(of: $0.regex, options: .regularExpression) != nil }
.first
.map { $0.dateFormat }
}
}
extension Date {
var formattedString: String {
return DateManager.shared.string(from: self)
}
var monthYearString: String {
return DateManager.shared.string(from: self, format: "MMMM yyyy")
}
}
extension String {
var date: Date? {
return DateManager.shared.date(from: self)
}
}
// Easily get a date from a string
let date = "20161230".date
// Or with time
let datetime = "2016-12-30 13:30:00".date
// And get a string from a date
let dateString = date?.formattedString
// Or just the month and the year
let monthYearString = date?.monthYearString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment