in iOS 12.1 I am getting the actual date by using the below code -
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "GMT")!
let startDate = dateFormatter.date(from: startDate)
print("the startdate - ",startDate)
// the startdate - Optional(2018-12-10 14:58:06 +0000)
let secondsFromGMT = TimeZone.current.secondsFromGMT()
let date = Date().addingTimeInterval(TimeInterval(secondsFromGMT))
print("the date from seconds gmt - ",date)
// the date from seconds gmt - 2018-12-10 16:10:32 +0000
let seconds = abs(Calendar.current.dateComponents([.second], from: startDate!, to: date).second ?? 0)
but in iOS 9.1 using the same code I am getting the different date as shown below
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "GMT")!
let startDate = dateFormatter.date(from: startDate)
print("the startdate - ",startDate)
// the startdate - Optional(2018-12-10 14:58:06 +0000)
let secondsFromGMT = TimeZone.current.secondsFromGMT()
// secondsFromGMT is 0
let date = Date().addingTimeInterval(TimeInterval(secondsFromGMT))
print("the date from seconds gmt - ",date)
// the date from seconds gmt - 2018-12-10 10:44:38 +0000
let seconds = abs(Calendar.current.dateComponents([.second], from: startDate!, to: date).second ?? 0)
So if you check the print statements I am not getting the actual current date. So how to achieve the same date in both the version without using any Webservices?
What do you mean "'Date()' is different in 12.1 and 9.1"? You mean the way it's displayed is different? As in you're getting different output from a date formatter in the 2 different OS versions?
The code you posted is using the date at the instant it's calculated in the line
let date = Date().addingTimeInterval(TimeInterval(secondsFromGMT))
. That code will generate a slightly different date every time you run it.The expression
Date()
gives you the current date at the instant the code is run. Run it 5 seconds later, and you'll get a date 5 seconds later. Take the time to install your code on a simulator running a different version of the OS and it will give different results because time has passed.Are you trying to write code that inputs a date string, converts it to a Date object, and then adds an offset to it? Why are you doing math with
secondsFromGMT
? That is not the right way to deal with time zone conversions.Explain what you're trying to do and we can help you write code that does that. It seems to me you have a fundamental misunderstanding of how to do date math in Cocoa.