I’m in the middle of quite a large project at the moment using server-side Swift (via the Perfect toolkit) that talks a lot to the Shopify Admin API.
After writing the same code several times to format dates to the RFC3339 standard like Shopify quite rightly desires, I face-palmed and refactored.
//
// DateExtensions.swift
// nw360Core
//
// Created by Jonathan Guthrie on 2018-03-15.
//
import Foundation
extension Date {
public func toDateString(_ fmt: String = "yyyy-MM-dd") -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = fmt
return dateFormatter.string(from: self)
}
/// 2018-03-15T13:40:46-04:00
public func toRFC3339String() -> String {
return toDateString("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
}
}
So this code quite simply helps the team avoid specifying dateFormatter
objects and format options over and over, and has a default string that we often use.
The toRFC3339String()
function leverages that same function but shortcuts us to the RFC3339 standard output.
It becomes wickedly simple, the team just needs to invoke the function on the date object.
Date().toDateString() // 2018-03-15T13:40:46-04:00
Date().toRFC3339String() // 2018-03-15