Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Optional string to date

I have this Optional(2015-07-27 19:29:50 +0000) as a string? and I want to convert it to a date (NSDate) but I can't figure it out I've been searching a lot for solutions but I am pretty new to coding so if anyone could help I would appreciate it.

This is what I am using to convert the string to a date currently.

note: dateString is Optional(2015-07-27 19:29:50 +0000)

dateFormatter = NSDateFormatter()
println(dateFormatter)
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)

I always get a nil value

like image 995
WDFAN23 Avatar asked Jul 27 '15 18:07

WDFAN23


People also ask

How to Convert normal String to Date?

// SimpleDateFormat SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy"); Date date = new Date(); String formattedDate = formatter. format(date); Date parsedDate = formatter. parse(formattedDate); // DateTimeFormatter LocalDate date = LocalDate.

How do you get a string out of optional?

Java 8 – Convert Optional<String> to String In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .


1 Answers

If you are getting nil from NSDateFormatter, you likely specified incorrect date format. Try this:

let strTime = "2015-07-27 19:29:50 +0000"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.dateFromString(strTime) // Returns "Jul 27, 2015, 12:29 PM" PST
like image 145
MirekE Avatar answered Sep 28 '22 16:09

MirekE