R
R
Roman19852015-05-08 12:27:15
iOS
Roman1985, 2015-05-08 12:27:15

IOS Swift timeIntervalSince1970 with correct time zone?

Help solve the problem. The end goal is to get the current time with the correct timezone in seconds since 1970.
So NSDate () does not know how to work with time zones, it gives me the time 3 hours ago.
Here is my code:

let date = NSDate()
        let dateFormatter = NSDateFormatter()
        dateFormatter.timeZone = NSTimeZone.localTimeZone()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
        var stringDate:String! = dateFormatter.stringFromDate(date) //Тут я получаю правильное время в строковом формате
         println("Нужное мне время в строковом формате \(stringDate)") //->2015-05-08 12:22:06 GMT+3
        let currentDate:NSDate = dateFormatter.dateFromString(stringDate)! //А здесь, у меня опять все возвращается, как было
        println("Нужное время NSDate \(currentDate)")//->2015-05-08 09:22:06 +0000
        

        //Но и тут соответственно секунды от этого числа: 2015-05-08 09:22:06 +0000  выводятся, т.к stringDate - строка, то к ней не применим метод timeIntervalSince1970
        let currentDateSec = Int(currentDate.timeIntervalSince1970)//+Отбрасываем милисекунды
        println("Текущее время в секундах\(currentDateSec)")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
smanioso, 2015-05-08
@smanioso

https://developer.apple.com/library/ios/documentat... - NSDate is behaving correctly! Don't be a rag and write the required method yourself - adding 2 numbers is not such a big problem.
PS: by the way, in any time zone , the same number of seconds have passed since that moment - isn't it?

A
An, 2015-05-09
@Flanker_4

You don't understand how "time works" at all.
I highly recommend finding some kind of doc on NSDate and time zones, get acquainted, and then climb into hell.
But the meaning is the following - nsdate always stores the "absolute" time
To display the same time in different time zones in the ui, use nsdateformater
And what you are doing is fundamentally wrong. Can you describe the problem you are trying to solve, why do you need this translation?
Here you are, for the knowledge of Zen https://developer.apple.com/library/ios/documentat...
See sections nsdate and time zone

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question