Home > other >  How to parse the string formate to another formate
How to parse the string formate to another formate

Time:09-17

How to parse date formate for following string

createdAt = "2021-09-03T19:33:44.791822 05:30" // from server end got value

      self.dateFormaterString(inputDate: "2021-09-03T19:33:44.791822 05:30")

      func dateFormaterString(inputDate: String) ->String{

        let formatter = DateFormatter()
 //       formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateStyle = .short
        if let date = formatter.date(from: inputDate){
            print(date)
        }
        return ""
    }

The following method dateFormaterString return nil breaking date value How to convert "2021-09-03T19:33:44.791822 05:30" into "09/07/2021"

CodePudding user response:

you need to set initially input dateformat formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSZ"

       func dateFormaterString(inputDate: String) ->String{
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSZ"
       
        guard let getDate = formatter.date(from: inputDate) else { return ""}
            
            formatter.dateStyle = .short 
           // if you want a exact op as 09/03/2021 then use 
           // formatter.dateFormat = "MM/dd/yyyy"
           return formatter.string(from: getDate)
        
    }

sample useage

   let value =  self.dateFormaterString(inputDate: "2021-09-03T19:33:44.791822 05:30")
    print(value)

you get the output as : 9/3/21

  • Related