Swift - extracting hours from NSDate, parsing string issue - ios

I receive a string in Json and first of all I have to do is to convert it into NSDate. The problem is, none of string formats I used is valid. the code goes as follows:
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
var output = formatter.dateFromString("2000-01-01T00:00:00.000Z")
let timeString = formatter.stringFromDate(output)
as far as I know, if I want to retrieve hours from NSData, I have to call formatter once more
formatter.dateFormat = "hh"
and call it on NSDate obtained from string. Am I right?
My first question is: how to make the determine proper date format so the output will not be evaluated to nil? The second question is: Do I get it right or there is a simpler method or generally way to retrieve the hours from the following string: "2000-01-01T00:00:00.000Z" ? I know I can do it via dealing with mere string without involving dateFormatter and NSDate, but won't such solution be vulnerable? Please advice me what's the simplest(and robust) way to deal with this.
Thanks in advance

First of all, you have your formatter wrong...
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"
var output = formatter.dateFromString("2000-01-01T00:00:00.000Z")
After that, you can get the hour component with
if let date = output {
var hours = NSCalendar.currentCalendar().component(.HourCalendarUnit, fromDate: date)
}

Related

How to get only time from date in swift

This question is not asked for the first time, but no solution works for me. I am getting time in String from Api response in the following format "14:45".
I want to compare this time with the current time, for this purpose I need to convert this string in Time formate(swift sports)
I always get nil after conversion
I have tried multiple ways but none of them worked for me and one is given for reference, I don't know what am I missing here
Thanks for any response
func stringToTime(str:String) -> Date{ // 14:45 passed here in str
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
print(str)
//here time string prints
let date = dateFormatter.date(from: (str))
print(date)
//date is nil here, should be 02:45 pm
return date!
}
If the time you get from the API is in 24h format you can do a string comparison
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let currentTime = formatter.string(from: Date())
let compare = currentTime.compare("14:45")
You might need to set the time zone for the DateFormatter to make sure it uses the same as the API
It seems like you want to transform a time string in one format to another format. Your method signature should look like this:
func changeFormat(str:String) -> String {
Note that you should not output a Date here, because Dates don't have formats. They will always be printed in the same way. What you need to do in this method is 2 things:
parse str to a Date using a DateFormatter, specifying the format HH:mm. You seem to assume that DateFormatter can automatically work this format out. It can't :(
format the Date object you just got using a DateFormatter, specifying the format hh:mm a. This produces a string, not a date.
(You could also consider having the method return a Date (then it would be called parseTime), and do the second step just before you show the date to the screen.)
func changeFormat(str:String) -> String {
let dateFormatter = DateFormatter()
// step 1
dateFormatter.dateFormat = "HH:mm" // input format
let date = dateFormatter.date(from: str)!
// step 2
dateFormatter.dateFormat = "hh:mm a" // output format
let string = dateFormatter.string(from: date)
return string
}

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

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

How to convert a string to Date in Swift2 2.0

I am working on convert a date string to NSDate, but I keep getting nil:
let strDate = self.DateList[0] // "2015-10-06T15:42:34Z"
print(strDate)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print (dateFormatter.dateFromString(strDate))
And the running result is:
2016-05-18T14:00:54.466Z
nil
I dont know why, any suggestions?
You got 2016-05-18T14:00:54.466Z in a print(strDate)
so, Your format should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
//---------------------------------2016-05-18 T 14:00:54.466 Z ----
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
print (dateFormatter.dateFromString(strDate))
You almost had it - just needed to escape out the 'Z':
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
A safer solution would be to use ZZZZZ as the time zone specifier or you could use of of the X specifiers.
The difference between Z and X is basically that X allows for literal Z to be used when the time offset is zero. See Date Field Symbol Table
Of course, you are also missing the millisecond part (.SSS). If you have two formats, one with milliseconds and one without milliseconds, you will have to use two different formatters.

How to convert String to NSDate?

I have string that I received whenever there is new remote notifications.I'm using parse for my Backend. And String that I retrieved come from "createdAt" column.
I've tried below code:
var ca = "2015-07-03T03:16:17.220Z"
var dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let date = dateFormater.dateFromString(ca)
println(date)
But the println is giving me nil, I think there is something wrong with my date format. How can I fix this?
You are missing the milliseconds. Thus:
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Note, when converting from the date string to a NSDate, you shouldn't quote the Z. If you quote the Z, it will match the literal Z character, but won't correctly reflect that this date string is actually Zulu/GMT/UTC.
If you want to create formatter that also goes the other way, converting NSDate objects to strings, in that case you should quote the Z, but in that case you must remember to explicitly set the timezone:
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormater.timeZone = NSTimeZone(forSecondsFromGMT: 0)
By the way, don't forget to set the locale as per Apple Technical Q&A 1480.
dateFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")

Resources