Search code examples
iosswiftnsdatensdateformatter

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 ?


Solution

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