Search code examples
swiftnsdateformatter

Date not coming correctly after formate in swift


I have separated date and time according to my code, then I have used DateFormatter but date not coming correctly.. why?

coming like this: Optional("08/15/0020")

  var formateFromdate: String?
  var formateTodate: String?

  func addDate(){

  var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
        fromDate = fromDateArr[0]
        fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
  var toDateArr   = toDateLabel.text!.components(separatedBy: ",")
        toDate = toDateArr[0]
        toTime  = toDateArr[1].replacingOccurrences(of: " ", with: "")
        
        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = "MM/dd/yyyy"
                 
        let showDateFrom = inputFormatter.date(from: fromDate)
        inputFormatter.dateFormat = "MM/dd/yyyy"
        formateFromdate = inputFormatter.string(from: showDateFrom!)
        print(formateFromdate)
        }

note: here fromDate = 08/15/2020 coming correct but after formate date not coming correct

OutPut:

    Optional("08/15/0020") it should be 08/15/2020


 

Solution

  • From the formatted date output, it seems the value of fromDate = fromDateArr[0] is "08/15/20" If that's the case, you will have to use a date format as below;

        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = "MM/dd/yy"
        
        let showDateFrom = inputFormatter.date(from: fromDate)
        inputFormatter.dateFormat = "MM/dd/yyyy"
        let formateFromdate = inputFormatter.string(from: showDateFrom!)
        print(formateFromdate)