How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

后端 未结 12 1909
北恋
北恋 2020-11-21 22:43

How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339?

The goal is a string that looks like this:

\"2015-01-01T00:0         


        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 23:38

    In the future the format might need to be changed which could be a small head ache having date.dateFromISO8601 calls everywhere in an app. Use a class and protocol to wrap the implementation, changing the date time format call in one place will be simpler. Use RFC3339 if possible, its a more complete representation. DateFormatProtocol and DateFormat is great for dependency injection.

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        internal static let rfc3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        internal static let localeEnUsPosix = "en_US_POSIX"
    }
    
    import Foundation
    
    protocol DateFormatProtocol {
    
        func format(date: NSDate) -> String
        func parse(date: String) -> NSDate?
    
    }
    
    
    import Foundation
    
    class DateFormat:  DateFormatProtocol {
    
        func format(date: NSDate) -> String {
            return date.rfc3339
        }
    
        func parse(date: String) -> NSDate? {
            return date.rfc3339
        }
    
    }
    
    
    extension NSDate {
    
        struct Formatter {
            static let rfc3339: NSDateFormatter = {
                let formatter = NSDateFormatter()
                formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
                formatter.locale = NSLocale(localeIdentifier: AppDelegate.localeEnUsPosix)
                formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
                formatter.dateFormat = rfc3339DateFormat
                return formatter
            }()
        }
    
        var rfc3339: String { return Formatter.rfc3339.stringFromDate(self) }
    }
    
    extension String {
        var rfc3339: NSDate? {
            return NSDate.Formatter.rfc3339.dateFromString(self)
        }
    }
    
    
    
    class DependencyService: DependencyServiceProtocol {
    
        private var dateFormat: DateFormatProtocol?
    
        func setDateFormat(dateFormat: DateFormatProtocol) {
            self.dateFormat = dateFormat
        }
    
        func getDateFormat() -> DateFormatProtocol {
            if let dateFormatObject = dateFormat {
    
                return dateFormatObject
            } else {
                let dateFormatObject = DateFormat()
                dateFormat = dateFormatObject
    
                return dateFormatObject
            }
        }
    
    }
    

提交回复
热议问题