Created
January 25, 2018 18:05
-
-
Save davbeck/3fe34c5ae0e2be45dabf95edd9de2b1d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import JavaScriptCore | |
/// Used to lookup our Bundle. | |
private class MomentBundleClass: NSObject {} | |
/// A wrapper around a moment.js object. | |
public struct Moment { | |
/// A shared context that new instances are created from. | |
public static let sharedContext: JSContext? = { | |
guard let context = JSContext() else { return nil } | |
guard let url = Bundle(for: MomentBundleClass.self).url(forResource: "moment", withExtension: "js") else { return nil } | |
guard let javascript = try? String(contentsOf: url) else { return nil } | |
_ = context.evaluateScript(javascript) | |
return context | |
}() | |
/// The underlying JavaScript value. | |
public let value: JSValue | |
/// Create a new moment instance from a date | |
/// | |
/// - Parameter date: The equivelant date to create the moment from. | |
public init?(_ date: Date) { | |
let timestamp = date.timeIntervalSince1970 * 1000 | |
// equivelant to `moment(timestamp);` | |
guard let value = Moment.sharedContext?.objectForKeyedSubscript("moment").call(withArguments: [timestamp]) else { return nil } | |
self.value = value | |
} | |
/// Generate a relative description from the current time | |
/// | |
/// See [http://momentjs.com/docs/#/displaying/fromnow/](http://momentjs.com/docs/#/displaying/fromnow/). | |
/// | |
/// - Returns: The description based on the amount of time from now. | |
public func fromNow() -> String? { | |
// `.fromNow();` | |
return value.invokeMethod("fromNow", withArguments: []).toString() | |
} | |
public enum CalendarFormat: String { | |
case sameDay | |
case nextDay | |
case nextWeek | |
case lastDay | |
case lastWeek | |
case sameElse | |
} | |
public func calendar(formats: [CalendarFormat: String]? = nil) -> String? { | |
let rawFormats = formats?.dictionaryMap({ ($0.rawValue, $1) }) | |
return value.invokeMethod("calendar", withArguments: [NSNull(), rawFormats.unwrapWithNSNull]).toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment