Reputation: 13
I am new to the swift library. I am using the calendar in swift and I want to show the events in calendar. The events are obtained from the Json API but when I compare the date it is showing an error.
This is the code
let data = event["date"] as? String
let newString = data?.replacingOccurrences(of: "/", with: "-")
self.FirstData = self.EventDates[0]
compare function
func compareDate(date : String){
let date = date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
====>>>>Error in line
let dateFromString : NSDate = dateFormatter.date(from: date)! as NSDate
dateFormatter.dateFormat = "yyyy-MM-dd"
let datenew = dateFormatter.string(from: dateFromString as Date)
print("datee",datenew)
}
Error: fatal error: unexpectedly found nil while unwrapping an Optional value
How to compare date or resolve this issue.
Upvotes: 0
Views: 3568
Reputation: 1457
Your app is crashing because of date string was not in the same format which was assigned to dateformatter
. Because of that date object return nil value.
And you force nil
value to convert NSDate
object. Because of that app is crashing.
You just need to change your compare date method as below:
func compareDate(date : String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateFromString = dateFormatter.date(from: date)
print("datee", dateFromString ?? "")
return dateFromString
}
By doing this you can able to create the Date
object.
Upvotes: 0
Reputation: 1607
date(from:)
returns an optional Date
simply because it may fail to properly convert the given string. As you cannot be sure when this happens you must not force unwrap the result (dateFormatter.date(from: date)!
) but rather safely unwrap the optional, i. e. using this construct:
if let dateFromString: NSDate = dateFormatter.date(from: date) as NSDate {
...
}
Upvotes: 1
Reputation: 986
try this :-
func convertDate(date:String) -> String {
let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale // save locale temporarily
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// date format getting from server
dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
let date = dateFormatter.date(from: date)!
//date format you want
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = tempLocale // reset the locale
let dateString = dateFormatter.string(from: date)
print("EXACT_DATE : \(dateString)")
return dateString
}
Upvotes: 2
Reputation: 1874
try this to change date format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateFormatter.dateFromString("2012-12-06 T 06:00:00 ")
dateFormatter.dateFormat = "yyyy-MM-dd"
let goodDate = dateFormatter.stringFromDate(date!)
Upvotes: 0