Convert UTC to local time with NSDateFormatter

后端 未结 3 1724
悲哀的现实
悲哀的现实 2020-12-05 03:24

I am getting the following string from a server in my iOS app:

20140621-061250

How can I convert it to the local time?

3条回答
  •  长情又很酷
    2020-12-05 04:16

    One possible solution in Swift using NSDate extension (maybe it could help future viewers of this question):

    import UIKit
    
    // For your personal information: NSDate() initializer 
    // always returns a date in UTC, no matter the time zone specified.
    extension NSDate {
        // Convert UTC (or GMT) to local time
        func toLocalTime() -> NSDate {
            let timezone: NSTimeZone = NSTimeZone.localTimeZone()
            let seconds: NSTimeInterval = NSTimeInterval(timezone.secondsFromGMTForDate(self))
            return NSDate(timeInterval: seconds, sinceDate: self)
        }
    
        // Convert local time to UTC (or GMT)
        func toGlobalTime() -> NSDate {
            let timezone: NSTimeZone = NSTimeZone.localTimeZone()
            let seconds: NSTimeInterval = -NSTimeInterval(timezone.secondsFromGMTForDate(self))
            return NSDate(timeInterval: seconds, sinceDate: self)
        }
    }
    

提交回复
热议问题