简体   繁体   中英

Date from String incorrect

I copied an extension for Swift's Date object somewhere that allows me to initialize a Date from a string as follows:

extension Date {
    init(fromString: String) {
        let str = "\(fromString) 12:00"
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm"
        dateStringFormatter.timeZone = NSTimeZone.default
        let d = dateStringFormatter.date(from: str)!
        self.init(timeInterval: 0, since: d)
    }
}

If, for instance, I pass "2016-10-16" as string for the custom initializer, the Date, when printed, should be "2016-10-16 22:00:00 +0000" , but right now it is: "2016-10-15 22:00:00 +0000" .

Any idea why?
Thanks!

Resolved the issue thanks to @jcaron.

Problem

The problem was that I mixed up 12 and 24 hour fomat when doing "hh:mm" . This is used for 12-hour formats while I wanted to use the 24-hour format.

Solution

To solve that, "hh:mm" needs to be changed to "HH:mm"

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