skip to Main Content

I am using date picker in my application. After selects particular date, It’s not able to converting to required format.

Datepicker date:

2021-07-21 13:53:38 +0000

expected format

21 July 2021

I am trying with below code

static func formatStringToDate(date: String) -> String? {
        
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        let datee = dateFormatter.date(from: "2021-07-21 13:53:38 +0000")


        dateFormatter.dateFormat = "d MMM yyyy"///this is what you want to convert format
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        let timeStamp = dateFormatter.string(from: datee!)

        return timeStamp ?? ""
     }

Any suggestions?

2

Answers


  1. Chosen as BEST ANSWER

    I have found solution. Here it is

    let date = formatToDate(date: datePicker.date) 
    
        static func formatStringToDate(date: Date) -> String? {
                        
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "dd MMMM yyyy"
                let formattedDate = dateFormatter.string(from: date)
                return formattedDate // "21 July 2022"
            
            }
    }
    

  2. Actually the correct way to write this to get you desired format should be:

    let date = formatToDate(date: datePicker.date) 
    
    static func formatStringToDate(date: Date) -> String? {
                    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMMM yyyy"
        let formattedDate = dateFormatter.string(from: date)
        return formattedDate // "21 July 2022"
        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search