Ali Ihsan URAL
Ali Ihsan URAL

Reputation: 1974

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 ?

Upvotes: 8

Views: 4226

Answers (2)

MRTLeo
MRTLeo

Reputation: 1

No, but you can always write an extension that does the job for you.

You should extend Date with a function that get the format (yyyy-MM-dd'T'HH:mm:ssZ) as an argument, create the special DateFormatter, then convert as usual with passages between String and Date.

Unluckily there is no standard way.

Upvotes: 0

Krunal
Krunal

Reputation: 79646

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

Upvotes: 5

Related Questions