Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created January 25, 2018 18:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/3fe34c5ae0e2be45dabf95edd9de2b1d to your computer and use it in GitHub Desktop.
Save davbeck/3fe34c5ae0e2be45dabf95edd9de2b1d to your computer and use it in GitHub Desktop.
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