NSDateformatter dateFromString AnyObject - ios

I have an array of AnyObjects of NSDates and I am trying to convert to weekdays like (Mon, Tue, Wed..)
The Array looks like this when I print it to the console:
[2014-12-03 22:16:26 +0000, 2014-12-05 22:16:26 +0000, 2014-12-11
22:16:26 +0000]
This is my Code:
var xAxisDates = [AnyObject]()
func dateformatter() {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let weekDayFormatter = NSDateFormatter()
weekDayFormatter.dateFormat = "EEE"
println(xAxisDates)
for i in xAxisDates{
let date = formatter.dateFromString(i as String)
println(weekDayFormatter.stringFromDate(date!))
}
}
The code crash at :
let date = formatter.dateFromString(i as String)
I have been trying all day to figure out what I am doing wrong, and read practically every question on NSDateFormatter but to no avail. I am down casting i as String because if I don´t I get error message AnyObject is not convertible to String. My feeling is that the type do not match up, but I am not sure, and I don´t know how to find out. I have attached the error message as picture if that helps. If you can recommend a tutorial or book or something on how to understand what is wrong I would appreciate it, as I am trying to learn.
Any help would be much appreciated !

The xAxisDates array contains NSDate objects, therefore
let date = formatter.dateFromString(i as String)
does not make any sense, and i as String already crashes because i is an NSDate
and not a String.
You just need to convert the dates to a string:
for i in xAxisDates {
println(weekDayFormatter.stringFromDate(i as NSDate))
}
or better check if the array elements actually are NSDate objects:
for i in xAxisDates {
if let date = i as? NSDate {
println(weekDayFormatter.stringFromDate(date))
}
}

extension NSDate {
var weekdayName: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"
return formatter.stringFromDate(self)
}
}
let myArrayOfAnyObjects:[AnyObject] = [NSDate()]
myArrayOfAnyObjects.first!.weekdayName // "Tuesday"

Related

NSDate from string is always nil

I receive dates as String like this one:
"2016-05-20T12:25:00.0"
I want to get its corresponding NSDate object, and I'm trying this way:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)
where dateStr is like the example I wrote first. I took the dateFormat string from this page, but I get a nil date, what is wrong there?
Thanks in advance
You have a few problems with your date format. First Y is for weekOfYear, D is for day of year. hh is used for 12 hours format, decimal second you should use capital S and you need to escape the 'T'
You should do as follow:
let dateString = "2016-05-20T12:25:00.0"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.dateFromString(dateString) {
print(dateFormatter.stringFromDate(date) ) // "2016-05-20T12:25:00.0\n"
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
print(dateFormatter.stringFromDate(date) )
}

Swift how to convert string to NSDate

I've got a date stored in my database and I want to retrieve it and display it nicely in my tableview cells.
The format it comes in from the database and stored in option1 is BO05151530
Where the first two letters have meaning in the program but are not needed for the date so I take those off using the substringFromIndex function.
So what is left is 05151530 where it represents MMddhmm
I would like to display it nicely like MM-dd # h:mm a
For example 12-05 # 3:45 am
Here is what I tried but unfortunately ns_date1 comes up as nil each time.
What would you suggest I do?
let date1 = option1.substringFromIndex(option1.startIndex.advancedBy(2))
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMddhhmm"
let ns_date1 = dateFormatter.dateFromString(date1)
Try this. you don't need to separate BO NSDateFormatter can handle extra string
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "'BO'MMddHHmm"
let ns_date1 = dateFormatter.dateFromString("BO05151530")
dateFormatter.dateFormat = "'BO' MM-dd # hh':'mm a"
let string = dateFormatter.stringFromDate(ns_date1!)
try
dateFormatter.dateFormat = "MMddHHmm"
HH is 24 hour format and hh is 12 hour format. you need the 24 one
Check out this app, this will help you know the right format and give you code
https://itunes.apple.com/ae/app/date-format-creator/id965645209?mt=12
NOTE: you need to add year to get a correct NSDate
I have this function :
class func getTheDateString(stringForInputDate: String, fromFormat inputFormat: String, toFormat outputFormat: String) -> String {
let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = inputFormat
formatter.timeZone = NSTimeZone.localTimeZone()
let dateForInput: NSDate = formatter.dateFromString(stringForInputDate)!
formatter.dateFormat = outputFormat
return formatter.stringFromDate(dateForInput)
}
and used it as:
let stringDate : String = "0515930" // "05151530"
if stringDate.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) < 8 {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHmm", toFormat: "MM-dd # h:mm a")]);
}else {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHHmm", toFormat: "MM-dd # h:mm a")]);
}
OUTPUT:
["05-15 # 9:30 AM"]
["05-15 # 3:30 PM"]

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;

Swift - extracting hours from NSDate, parsing string issue

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)
}

How to constuct NSDate object from String with milliseconds

I need to construct NSDate object from String, so I wrote the following code:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.dateFromString(string)
return date!
}
Unfortunately, the input string sometimes may contain milliseconds too. What can I do in this case? I don't find any way to read milliseconds (not in the day) according to the http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
Thanks in advance.
As far as I know, the format doesn't support "optional" fields. So you have to try the formats one by one:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
var date = formatter.dateFromString(string)
if date == nil {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
date = formatter.dateFromString(string)
}
return date!
}
You can try something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
A Swift 3 Solution
After a bit of trial and error with the date format this is what worked for me with Swift 3.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let date = formatter.date(from: "2017-03-11 13:16:31.177")!
debugPrint(dateFormatter.string(from: date))
and after a round trip results in the expected debug output of
"2017-03-11 13:16:31.177"
Note that using the format "yyyy-MM-dd'T'HH:mm:ss.SSS" resulted in formatter.date(from: returning a nil optional Date.
Are they important?
In DateFormatter you create your matching string in years, months, days, hours, mins, secs, but you don't need to. If your matching string does not contain any of them, formatter will just ignore them.

Resources