Swift ISO-8601 date formatting with iOS7 - ios

I really need your help guys. The following piece of code works fine in a Swift Playgound and with any iOS8 or 8.1 simulator. But with iOS7 and 7.1, the NSDate object is always set to nil.
The object dateString contains a JSON string (ISO 8601 format) like 2015-02-28T20:15:00+0100
I'm trying to convert this date string into a NSDate object with the following code :
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.ZZZ"
if let dateString = (json as NSDictionary).valueForKey("dateAndTime") as? String
{
let dateObject = dateFormatter.dateFromString(dateString)
}
Where's my mistake ? I'm getting confused!
Many thanks

The problem is with your time zone offset, your date format is not proper for that. Use the following format,
"yyyy-MM-dd'T'HH:mm:ssZZZZZ"

Related

Date() returns hour over 24

I have to send date from my iPhone through my app to server, but I was surprised that the date had stored as NULL (not always) in server, that's the code used for that:
timeS = (Date().millisecondsSince1970)
// make some assertions on timeS
let date = Date(timeIntervalSince1970: timeS)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = dateFormatter.string(from: date)
return dateString
It seems like the c# code in the server side tried to convert the string to date and it failed, so it was stored NULL.
So recently I tried to send the date without any modifications in a string to see what happened:
self.backS.sendLocation(msg: "data fitched \(Date())")
and that's what I found in the database:
data fitched 2018-05-08 77:45:44 AM +0000
it must be:
data fitched 2018-05-08 07:45:44 AM +0000 (because that was the time for the server)
I don't know why is that happened!!
I really appreciate anybody's help, thanks in advance.
Try to get your current date and time like this in Swift.
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let result = formatter.string(from: date)
self.backS.sendLocation(msg: "data fetched \(result)")
Your result will be like this.
"2018-05-12 14:34:51 +0000"
To send the date to server you should rather use Unix timestamp, instead of date in string format.
But, if you insist on a string, you should use DateFormatter. When using DateFormatter you should always set the locale property of your formatter. That ensures the formateer will return consistens results, regardless of your phone's regional settings.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let dateString = formatter.string(from: Date())
It's important to set the locale property before you set the dateFormat property.
If you don't set the locale property, the formatter might return nil when working with 24-format on devices with 12-hour format set, and vice versa.
Source: Technical Q&A QA1480

Formatting JSON date to Swift date doesn't work

I'm trying to format this date: 2018-01-10T11:57:21.153 to Swift Date object like this:
let dateSentString = jsonDict["date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateSentString)!
For some reason, the app crashes on the last line.
What am I doing wrong? Thanks!
change the milli seconds format use 'SSS' specifier (with number of S's equal to number of digits of milliseconds ). for more information you get here
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
from
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
Full code
let dateSentString = "2018-01-10T11:57:21.153"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.date(from: dateSentString)!
print(date)
You have to first set formatter for date you are getting from JSON and then another formatter for the date you want.
First convert string fro JSON to a date variable by setting same format coming in JSON object .
Then you have to re-format that date variable into format you want.
I can write code if you want but it is better to try yourself.
Happy Coding

Why does this date formatting not work?

I am puzzled. I read the international spec for formats...yet it seems to return a nil in playgrounds and in code.
let dateString = "022018"
let formatter = NSDateFormatter()
formatter.setLocalizedDateFormatFromTemplate("MMyyyy")
let date = formatter.dateFromString(dateString)
I can't change the stringDate to be 02/2018...I have to maintain that format..what is the right mask then to get some output?
The problem is the call to formatter.setLocalizedDateFormatFromTemplate. I don't think this means what you think it does. You are turning a string to a date, not a date to a string. Just set the formatter's dateFormat. This works fine (Swift 3, hope you don't mind):
let dateString = "022018"
let formatter = DateFormatter()
formatter.dateFormat = "MMyyyy"
let date = formatter.date(from:dateString)

What should be the format of a string to convert into NSDate?

I'm getting following two types of strings from server:
2016-07-28T12:25:31.922247
2016-07-28T13:39:13
I want to convert them into NSDate. I'm using following snippet to convert but it's failing:
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss"
I'm not getting the desired output.
If you doesn't care the fraction of second then you can remove it like this.
var strDate = "2016-07-28T12:25:31.922247"
if strDate.rangeOfString(".") != nil{
let arr = strDate.characters.split{$0 == " "}.map(String.init)
strDate = arr[0]
}
//Now you can convert this string to date using same date format
let formatter= NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.dateFromString(strDate)
You can get the exact format from this Link
For the second string use this
yyyy-MM-dd'T'HH:mm:ss
You need to quote the "T" (or any alpha characters that should be present in literal form), try:
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
Note that this will only parse your second string. To parse your first string you'll need to use:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if you care about the fractional seconds. Since NSDateFormatter is a literal parser it doesn't allow you to easily parse either format, if you have to parse both you'll just need to pass it to one, if that fails pass to the other.
Your date format works in 2016-07-28T13:39:13 but add 'T'
Example: yyyy-MM-dd'T'HH:mm:ss.
But for the 2016-07-28T12:25:31.922247 you need clarifies that this means 922247
the truth had never seen anything like it, but I would try with yyyy-MM-ddTHH:mm:ssZ

Create NSDate from "2015-01-17T20:00Z" in iOS Swift Project

I'm working with some JSON data that returns a dateTime in this format: "2015-01-17T20:00Z", when I attempt to turn this into an NSDate object, I'm always left with nil. I've read through several of the tutorials and answers here on SO, Apple's NSDate / NSDateFormatter / Date Formatting docs, and pinged a few IRC channels.
Can anyone tell me what I'm doing wrong and a possible work around?
My failing code in a Swift playground:
let dateString = "2015-01-17T20:00Z"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-ddThh:mmZ"
let d = dateStringFormatter.dateFromString(dateString)
println(d)
Output: "Optional(2015-01-17 06:00:00 +0000)"
Working code in the same Swift playground:
let dateString = "2015-01-17"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
let d = dateStringFormatter.dateFromString(dateString)
println(d)
Output: "nil"
You have to format it like this "yyyy-MM-dd\'T\'HH:mmZ". You can try it also with this extension:
extension String {
func toDateFormattedWith(format:String)-> NSDate {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.dateFromString(self)!
}
}
as mentioned by rmaddy your date is UTC format so we will escape only the "T" as follow:
"2015-01-17T20:00Z".toDateFormattedWith("yyyy-MM-dd\'T\'HH:mmZ") // "Jan 17, 2015, 6:00 PM"
If you need some reference formatting your dates you can use this one;

Resources