Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSDate to String in iOS Swift [duplicate]

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)
like image 490
iOS Avatar asked Mar 01 '17 06:03

iOS


People also ask

How to convert NSDate to string in Swift?

You can use this extension: extension Date { func toString(withFormat format: String) -> String { let formatter = DateFormatter() formatter. dateFormat = format let myString = formatter. string(from: self) let yourDate = formatter.

How to format date to string Swift?

You have to declare 2 different NSDateFormatters , the first to convert the string to a NSDate and the second to print the date in your format. Try this code: let dateFormatterGet = NSDateFormatter() dateFormatterGet. dateFormat = "yyyy-MM-dd HH:mm:ss" let dateFormatterPrint = NSDateFormatter() dateFormatterPrint.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I get todays date in Swift?

Get current time in “YYYY-MM–DD HH:MM:SS +TIMEZONE” format in Swift. This is the easiest way to show the current date-time.


2 Answers

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

like image 144
Anbu.Karthik Avatar answered Oct 20 '22 16:10

Anbu.Karthik


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")
like image 76
roy Avatar answered Oct 20 '22 16:10

roy