首页 文章

如何将服务器响应日期转换为本地时区?

提问于
浏览
1

在api呼叫响应中,我在不同的时区获得日期 . 我想将其转换为用户的本地时区,用户可以从ios时区列表中选择任何时区 . 这都是本地的 . 我们永远不会将选定的用户时区发送到服务器 .

在进行任何api调用时,我可以说我在选择器中创建了一个具有所选开始日期的事件 . 我应该发送全局时区而不是用户选择的时区,因为它是应用程序的本地时区 .

目前我正在更改defaultTimeZone选择,以便我得到正确的当前日期等 . 并使用NSDateFormatter与setTimeZone ... [NSTimeZone timeZoneWithName ...

这是更好的方法来更改应用程序本地的defaultTimeZone吗?在将NSdate发送到服务器时,如何将NSdate转换回全局日期?

1 回答

  • 3

    NSDate 是一个时间点,你可以称之为绝对时间 . 这个时间对于地球上的每个地方都是一样的 . NSDate 不表示格式化为特定位置的人的喜好的时间 . 这种差异非常重要 .

    单个NSDate()可以在多个时区中具有多个表示 .

    为了使其更直观,这5个时钟都代表一个时间点( NSDate 实例):

    enter image description here

    它们只是显示了同一时间点的不同表示 .

    可以说这些时钟就是 NSDateFormatter.stringFromDate() . 他们将绝对时间点转换为局部表示 .

    要在不同的时区之间进行转换,请不要更改 NSDate ,而是更改 NSDateFormatter 的时区 . 如果从服务器获取的日期字符串是UTC,则需要使用UTC作为timeZone的NSDateFormatter:

    let utcDateFormatter = NSDateFormatter()
    utcDateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    utcDateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    utcDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    let serverString = "2015-04-03 12:34:56" // date from server, as date representation in UTC
    let date = utcDateFormatter.dateFromString(serverString) // date you got from server, as point in time
    

    要向用户显示该服务器时间,请使用该NSDate并将其放入另一个dateFormatter:

    // display absolute time from server as timezone aware string
    let localDateFormatter = NSDateFormatter()
    localDateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
    localDateFormatter.timeStyle = NSDateFormatterStyle.LongStyle
    let localDateString = localDateFormatter.stringFromDate(date)
    

    如果要将日期字符串发送回服务器,可以使用NSDate并将其放入UTC dateFormatter .

    // send back time to server
    let dateString = utcDateFormatter.stringFromDate(NSDate())
    

相关问题