Having trouble using NSDateFormatter in Swift, can someone help? Below code prints nothing.
var dateFormatter = NSDateFormatter()
println(dateFormatter.stringFromDate(NSDate()))
Make you set either the dateFormat (or dateStyle).
Here's a complete example that breaks it down to make it easier to see what you're missing.
The specific line you want to pay attention to is one where you need to set the dateFormat of the dateFormatter. Here we're setting it to "yyyy-MM-dd" which will give an output like "2014-06-22".
func formatADate() {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let d = NSDate()
let s = dateFormatter.stringFromDate(d)
println(s)
}
Then you can call formatADate().
Check out the NSDateFormatter reference for further info.
Did you make sure to set the date style? If you don't, it will output an empty string.
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
println(dateFormatter.stringFromDate(NSDate()))
If you are using UIDatePicker
:
@IBAction func whenDateChanged(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let strDate = dateFormatter.stringFromDate(datePicker.date)
self.dateLabel.text = strDate
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With