Convert NSDate to String in iOS Swift [duplicate] Convert NSDate to String in iOS Swift [duplicate] ios ios

Convert NSDate to String in iOS Swift [duplicate]


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 herefor e.g , do like

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

you get the output as

enter image description here


I always use this code while converting Date to String . (Swift 3)

extension Date{    func toString( dateFormat format  : String ) -> String    {        let dateFormatter = DateFormatter()        dateFormatter.dateFormat = format        return dateFormatter.string(from: self)    }}

and call like this . .

let today = Date()today.toString(dateFormat: "dd-MM")


DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {    func asString(style: DateFormatter.Style) -> String {    let dateFormatter = DateFormatter()    dateFormatter.dateStyle = style    return dateFormatter.string(from: self)  }}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()myDate.asString(style: .full)   // Wednesday, January 10, 2018myDate.asString(style: .long)   // January 10, 2018myDate.asString(style: .medium) // Jan 10, 2018myDate.asString(style: .short)  // 1/10/18