为什么date.dateByAddingTimeInterval(秒)关闭1小时?

时间:2015-01-22 17:14:22

标签: ios swift nsdate

为什么.dateByAddingTimeInterval()返回差异1小时?夏令时目前无效,因此不应影响它。我做错了什么?

http://www.timeanddate.com/date/durationresult.html?m1=4&d1=25&y1=2011&m2=1&d2=1&y2=2043&h1=0&i1=0&s1=0&h2=1&i2=46&s2=40

import Foundation

struct Gigasecond{

        static func newDate(input:String, format:String = "yyyy-MM-dd" ) -> NSDate{
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = format
            return dateFormatter.dateFromString(input) ?? NSDate.distantFuture() as NSDate
        }

        static func from(dateInString:String) -> NSDate{

            var dateIn = newDate(dateInString)

            return dateIn.dateByAddingTimeInterval(1_000_000_000)

        }

    }

    let newDate23 = Gigasecond.newDate("2043-01-01T01:46:40", format:"yyyy-MM-dd'T'HH:mm:ss")
    println(Gigasecond.from("2011-4-25").timeIntervalSinceDate(newDate23)) //-3600.0  or 1 hour ( 60*60 )

1 个答案:

答案 0 :(得分:1)

如果明确设置timeZone格式化程序会发生什么?

struct Gigasecond{

    static func newDate(input:String, format:String = "yyyy-MM-dd" ) -> NSDate{
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format

        // Explicitly set the time Zone for the formatter
        dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)

        return dateFormatter.dateFromString(input) ?? NSDate.distantFuture() as NSDate
    }

    static func from(dateInString:String) -> NSDate{

        var dateIn = newDate(dateInString)

        return dateIn.dateByAddingTimeInterval(1_000_000_000)

    }

}

let newDate23 = Gigasecond.newDate("2011-4-25T01:46:40", format:"yyyy-MM-dd'T'HH:mm:ss")
println(Gigasecond.from("2011-4-25").timeIntervalSinceDate(newDate23))