Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Convert Date to Date with dateFormat

I know the convert Date to String // String to Date

with

let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"

let date = formatter.date ( from: String ) 

or

let string = formatter.string ( from: Date )

but I want to convert Date to Date with formatting like this "yyyy-MM-dd'T'HH:mm:ssZ" to "yyyy-MM-dd" in Date format.

Is there anyway to do this with one line ?

like image 564
Ali Ihsan URAL Avatar asked May 15 '18 14:05

Ali Ihsan URAL


1 Answers

Answer to your question: No.

You can create a date/string extension, that can solve your problem in one-line. Note, Date object is a date object. It does not have any format (like string).

May this help you:

extension String {


    func convertDateString() -> String? {
        return convert(dateString: self, fromDateFormat: "yyyy-MM-dd'T'HH:mm:ssZ", toDateFormat: "yyyy-MM-dd")
    }


    func convert(dateString: String, fromDateFormat: String, toDateFormat: String) -> String? {

        let fromDateFormatter = DateFormatter()
        fromDateFormatter.dateFormat = fromDateFormat

        if let fromDateObject = fromDateFormatter.date(from: dateString) {

            let toDateFormatter = DateFormatter()
            toDateFormatter.dateFormat = toDateFormat

            let newDateString = toDateFormatter.string(from: fromDateObject)
            return newDateString
        }

        return nil
    }

}

Use one-line code:

let newDateString = "my date string".convertDateString()
like image 188
Krunal Avatar answered Nov 13 '22 09:11

Krunal