Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble using NSDateFormatter (stringFromDate) in Swift

Having trouble using NSDateFormatter in Swift, can someone help? Below code prints nothing.

var dateFormatter = NSDateFormatter()
println(dateFormatter.stringFromDate(NSDate()))
like image 516
user3764586 Avatar asked Jun 22 '14 20:06

user3764586


3 Answers

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.

like image 67
louielouie Avatar answered Nov 15 '22 12:11

louielouie


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()))
like image 20
Connor Avatar answered Nov 15 '22 13:11

Connor


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

}
like image 24
Vinod Joshi Avatar answered Nov 15 '22 11:11

Vinod Joshi