Search code examples
iosswiftswift3nsdateformatter

Convert NSDate to String in iOS Swift


I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.

 let formatter = DateFormatter()
 let myString = (String(describing: date))
 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let yourDate: Date? = formatter.date(from: myString)
 formatter.dateFormat = "dd-MMM-yyyy"
 print(yourDate)

Solution

  • you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

    let formatter = DateFormatter()
    // initially set the format based on your datepicker date / server String
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    let myString = formatter.string(from: Date()) // string purpose I add here 
    // convert your string to date
    let yourDate = formatter.date(from: myString)
    //then again set the date format whhich type of output you need
    formatter.dateFormat = "dd-MMM-yyyy"
    // again convert your date to string
    let myStringDate = formatter.string(from: yourDate!)
    
    print(myStringDate)
    

    you get the output as

    enter image description here