简体   繁体   中英

string like “2016-06-06” to Date object in Swift 3

I am new to swift 3, the way I found is

extension Date
{
    init(dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
        let d = dateStringFormatter.date(from: dateString)!
        self(timeInterval:0, since:d)
    }
}`

in self(timeInterval:0, since:d)

raise error Cannot call value of non-function type 'Date'

also I doesn't see this error before. Anyone please help me and explain it

更改为: self.init(timeInterval:0, since:d)

The result dateStringFormatter.date(from: dateString)! is a Date , you have no need to call another initializer in such cases for struts.

extension Date
{
    init(dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
        self = dateStringFormatter.date(from: dateString)!
    }
}
print(Date(dateString: "2016-09-27")) //->2016-09-26 15:00:00 +0000

I'm not sure using user's default TimeZone is what you intend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM