0

HI I am trying to formate date from string (08-05-1988) I want to convert to date as given below, output also given below,

let dateString = "08-05-1988"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateFromString = dateFormatter.date(from: dateString)
let stringValue = String(describing: dateFromString)

out put : Optional(1988-05-07 18:30:00 +0000)

Then, I want to format the out put date from (1988-05-07 18:30:00 +0000) to other format as given below. But, when format the string to Date is nil

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd hh:mm:ss Z"
let date = dateFormatter.date(from: dateString)
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyyy"
let formatedDate:String = formatter.string(from: date!)

Expected Output : 08-May-1988

0

3 Answers 3

1

The output Optional(1988-05-07 18:30:00 +0000) is the result of the description of a Date object. It's not related to any given string format.

To convert 08-05-1988 to 08-May-1988 you can simply use

let dateString = "08-05-1988"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateFromString = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "dd-MMM-yyyy"
let formatedDate = dateFormatter.string(from: dateFromString!)
1
let date = Date()

let format = DateFormatter()

format.dateFormat = "dd-MM-yyyy"

let formatDate = format.string(from: date)
0

You're calling dateFormatter.date on dateString instead of dateFromString. Since "08-05-1988" doesn't match the specified format of "yyyy-mm-dd hh:mm:ss Z", dateFormatter.date returns nil.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.