I tried from my end and browsed too. Might be this question have been asked many times. I parsed weather response of city's (ex: Mar del Plata) based on there timezone. I want time in HH:mm format. Below is the sample JSON response.
"sunrise": "2016-07-10T08:05:02-0300", "sunset": "2016-07-10T17:46:29-0300"
My code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
guard let date = dateFormatter.dateFromString(dateString) else {
assert(false, "no date from string")
}
dateFormatter.dateFormat = "HH:mm"
//dateFormatter.timeZone = NSTimeZone(name: "UTC")
return dateFormatter.stringFromDate(date)
Whenever I print or display date string in label the hours is getting changed. I WANT exact time coming in response.
My temporary solution for the above is
// Begin - Its a temperory solution
if dateString.contains("T") {
print("dateString.contains(T)")
let myArray = dateString.componentsSeparatedByString("T")
if myArray.count > 0 {
let str = myArray[1]
if str.contains("+") {
print("(str.contains(+))")
let myArr = str.componentsSeparatedByString("+")
if myArr.count > 0 {
let str1 = myArr[0]
if str1.contains(":") {
print("str1.contains(:)")
let myAr = str1.componentsSeparatedByString(":")
if myAr.count > 0 {
let str2 = myAr[0]
let str3 = myAr[1]
let str4 = "\(str2):\(str3)"
print(str4)
return str4
}
//print(myAr)
}
}
}
if str.contains("-") {
print("(str.contains(-))")
let myArr = str.componentsSeparatedByString("-")
if myArr.count > 0 {
let str1 = myArr[0]
if str1.contains(":") {
print("str1.contains(:)")
let myAr = str1.componentsSeparatedByString(":")
if myAr.count > 0 {
let str2 = myAr[0]
let str3 = myAr[1]
let str4 = "\(str2):\(str3)"
print(str4)
return str4
}
//print(myAr)
}
}
}
}
}
// End - Its a temporary solution
I want a better solution instead of my temporary one.
Edit1: As I mentioned, I want same time coming in JSON response by discarding the timezone.
Please suggest me and guide me how to deal with time zone in future. Hope you guys understand, what am I upto. Sorry for my poor English.
Thanks in Advance.
If you absolutely don't care about the timezone, you can simply trim it off:
let sunrise = "2016-07-10T08:05:02-0300"
let sunriseNoTimezone = sunrise.substringToIndex(sunrise.endIndex.advancedBy(-5))
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let date = formatter.dateFromString(sunriseNoTimezone)
print(date)