Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date formatting not working in Swift 3

I'm having a problem with NSDate in a function. Essentially, the formatting is not working, and I need another set of eyes to see what I'm doing wrong.

Code:

 @IBOutlet weak var dateField: NSTextField!

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
let currentDate = NSDate()

convertedDateString = dateFormatter.string(from:currentDate as Date)
dateField.stringValue = convertedDateString as String

print("convertedDate: ", convertedDateString)
print("dateField.stringValue: ", dateField.stringValue)

Result:

convertedDate: July 25 2016
dateField.stringValue: 7/25/16

like image 792
ICL1901 Avatar asked Jul 25 '16 10:07

ICL1901


People also ask

What is the date format in Swift?

dateFormat = "yyyy-MM-dd'T'HH:mm:ss.

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

Date().toString() // convert date to string with userdefined format.

extension Date {
        func toString() -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMMM dd yyyy"
            return dateFormatter.string(from: self)
        }
    }
like image 161
SaRaVaNaN DM Avatar answered Oct 02 '22 09:10

SaRaVaNaN DM


Extension for getting string against date formats

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

Date().toString(format:"H:mm")
like image 28
Muhammad Adnan Avatar answered Oct 02 '22 09:10

Muhammad Adnan