Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsing dates? #15

Closed
basememara opened this issue May 3, 2016 · 2 comments
Closed

Parsing dates? #15

basememara opened this issue May 3, 2016 · 2 comments

Comments

@basememara
Copy link
Contributor

basememara commented May 3, 2016

I'm guessing you left out dates because it would open up a can of worms. I added an extension that works, but is inconsistent with the rest of the API's:

extension JSON {
    public subscript(index: String, dateFormat dateFormat: String) -> NSDate? {
        let formatter = NSDateFormatter()
        formatter.dateFormat = dateFormat

        if let value = self[index].string,
            let date = formatter.dateFromString(value) {
                return date
        }

        return nil
    }
}

Then you use it like this:

date = json["date", dateFormat: "yyyy-MM-dd'T'HH:mm:ss"]

Any thoughts or suggestions on adding support for dates?

@basememara
Copy link
Contributor Author

I took another pass at it that's more consistent and cleaner:

extension JSON {

    /// The value as a date or nil if not present/convertible
    public var dateValue: NSDate? { return dateValue("yyyy-MM-dd'T'HH:mm:ss") }

    /**
        The value as a date or nil if not present/convertible.
        - parameter dateFormat: A string for formatting the date.
        - returns: A new instance of date or nil if its object cannot be formatted.
    */
    public func dateValue(dateFormat: String) -> NSDate? {
        let formatter = NSDateFormatter()
        formatter.dateFormat = dateFormat

        return dateValue(formatter)
    }

    /**
        The value as a date or nil if not present/convertible.
        - parameter dateFormat: A date formmatter for converting the date.
        - returns: A new instance of date or nil if its object cannot be formatted.
    */
    public func dateValue(dateFormatter: NSDateFormatter) -> NSDate? {
        guard let value = string,
            let date = dateFormatter.dateFromString(value)
                else { return nil }

        return date
    }
}

Now you can use it like this:

json["date1"].dateValue
json["date2"].dateValue("dd-MM-yyyy")

let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
json["date3"].dateValue(formatter)

I created a PR #16, let me know what you think 😁

@delba
Copy link
Owner

delba commented May 3, 2016

Discussion in #16

@delba delba closed this as completed May 3, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants