Skip to content

Instantly share code, notes, and snippets.

@chrisiona
Last active May 8, 2018 01:38
Show Gist options
  • Save chrisiona/af2200bc8790a46d7c577f6e3680587b to your computer and use it in GitHub Desktop.
Save chrisiona/af2200bc8790a46d7c577f6e3680587b to your computer and use it in GitHub Desktop.
Extend the SwiftyJSON module with a .date type (Swift3)
//
// SwiftyJsonExtension.swift
//
// Created by Chris Iona on 02/12/16.
// MIT License.
//
// Date extension for SwiftyJSON module
// https://github.com/SwiftyJSON/SwiftyJSON
//
// Assumes that you already have SwityJSON installed and available
//
import Foundation
import SwiftyJSON
extension JSON {
public var date: Date? {
get {
if let epoch = self.double {
// Convert epoch Interval (aka Double) to Date Object
return Date(timeIntervalSince1970: epoch)
}
return nil
}
set {
if let newValue = newValue {
// Store date object as epoch Interval (aka Double)
self.double = newValue.timeIntervalSince1970
} else {
self.object = NSNull()
}
}
}
}
//
// Example usage in your Controller
//
/*
// Get the current point in time as Date (Struct)
let currentTime = Date()
// Create instance of JSON (SwiftyJson)
var json: JSON = [:]
// SET — becomes an Interval (aka Double)
json["currentTime"].date = currentTime
// GET — becomes an instance of Date
print( json["currentTime"].date! )
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment