Skip to content

Instantly share code, notes, and snippets.

@mbogh
Last active October 29, 2016 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbogh/b1a31cf7c7377398a780 to your computer and use it in GitHub Desktop.
Save mbogh/b1a31cf7c7377398a780 to your computer and use it in GitHub Desktop.
import Foundation
extension NSDate {
convenience init?(WCFDateString dateString: String) {
// First remove nonsense from dateString: /Date(_)/
let dateStringSane = dateString.stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
// Make sure dateStringSane is at least 3 characters
guard dateStringSane.characters.count >= 3 else { return nil }
// Trim ms from the string
let dateStringTrimmed = dateStringSane.substringToIndex(dateStringSane.endIndex.advancedBy(-3))
// Convert to Double
guard let timeIntervalSince1970 = Double(dateStringTrimmed) else { return nil }
self.init(timeIntervalSince1970: timeIntervalSince1970)
}
}
NSDate(WCFDateString: "/Date(1450093658000)/") // "Dec 14, 2015, 12:47 PM"
NSDate(WCFDateString: "/Date(1450093658)/") // "Jan 17, 1970, 7:48 PM"
NSDate(WCFDateString: "/Date(1455)/") // "Jan 1, 1970, 1:00 AM"
NSDate(WCFDateString: "/Date(145)/") // nil
NSDate(WCFDateString: "/Date(14)/") // nil
NSDate(WCFDateString: "/Date(1)/") // nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment