-3

I have a date of type date and has a format "yyyy-MM-dd HH:mm:ss" and I would like to convert it to "yyyy-MM-dd". I am not sure how to achieve this since the date is of type Date.

Example :

let dateComponents: Date? = dateFormatterGet.date(from: "2019-03-11 17:01:26")

Required output :

Date object of format type "yyyy-MM-dd"

It is important to note that I have only date objects and no string.
kaddie
  • 233
  • 1
  • 5
  • 27

3 Answers3

0

You have a date of type String, not Date.

You use one DateFormatter to convert it to Date (check that the DateFormatter doesn't return nil).

Then you use another DateFormatter to convert the Date to a string.

Please don't use "dateComponents" as a variable name. You never, ever touch date components in your code. And you don't need to specify the type, just "let date = ..." or better "if let date = ..." checking for nil.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

you can use like this:

        let now = Date().UTCToLocalDateConvrt(format: "yyyy-MM-dd HH:mm:ss",convertedFormat : "yyyy-MM-dd")

put below function in Date extension class:

extension Date {
    func UTCToLocalDateConvrt(format: String,convertedFormat: String) -> Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
            let timeStamp = dateFormatter.string(from: self)
            dateFormatter.dateFormat = convertedFormat
            guard let date = dateFormatter.date(from: timeStamp)else{
                return Date()
            }
            return date
        }
}
Anil Kumar
  • 1,830
  • 15
  • 24
0
func formatDate(yourDate: String) -> String { //  "yyyy-MM-dd HH:mm:ss"
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" // here you can change the format that enters the func

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "yyyy-MM-dd" // here you can change the format that exits the func

    if let date = dateFormatterGet.date(from: yourDate) {
        return dateFormatterPrint.string(from: date)
    } else {
        return nil
    }
}

use it like this:

formatDate(yourDate: "2019-03-11 17:01:26")

it will return an optional string, that can be nil, make sure you are safety unwrap it (if let , guard let)

answer based on link

Toto
  • 593
  • 7
  • 20
  • My date is of type Date so this ``` formatDate(yourDate: String)```should be taking in an object of type Date not string – kaddie Mar 11 '20 at 16:56