SWIFT: How do I add hours to NSDate object

后端 未结 4 1756
逝去的感伤
逝去的感伤 2021-01-02 18:18

I generate a NSDate object from string.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = \"yyyy-MM-dd HH:mm:ss\"
dateFormatter.timeZone = NS         


        
4条回答
  •  自闭症患者
    2021-01-02 19:06

    You're asking the wrong question. This is what's known as an "XY Problem". You should be asking "How do I display a date string I get from a web server in the user's local time zone."

    NSDate represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.

    The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
    let date = dateFormatter.dateFromString(dateFromService) 
    
    let outputDatedateFormatter = NSDateFormatter()
    outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    //leave the time zone at the default (user's time zone)
    let displayString = outputDateFormatter.stringFromDate(date)
    println("Date in local time zone = \(displayString)")
    

提交回复
热议问题