Swift Accessing year from UIDatePicker

2020-07-27 06:06发布

Just barely getting into iOS development using swift and getting a little overwhelmed sometimes trying to look at documentation and understand it. I am also currently running through Simon Allardice's iOS app development with swift essential training on Lynda.com and had a question regarding one of the objects we have instantiated in the WhatDay example.

We basically are setting up a UIDatePicker object from which we are extracting what day of the week we are looking at with the NSDateFormatter object at which point I was wondering,

which property would we need to access to get ahold of the current year that the user scrolled the wheel to?

So far we have this code to access the day of the week it was,

@IBACTION func displayDay(sender: AnyObject) {

// grab the selected data from the date picker
var chosenDate = self.datePicker.date

// create an NSDateFormatter
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"

// grab the day and create a message
let day = formatter.stringFromDate(chosenDate)
let result = "That was a \(day)"

}

Also, he says we can use the date formatter "EEEE" to format for day of the week but I couldn't find any documentation on that online what the string codes are, any advice on where to find this information?

2条回答
手持菜刀,她持情操
2楼-- · 2020-07-27 06:55

var datePicker = UIDatePicker() use it

查看更多
beautiful°
3楼-- · 2020-07-27 07:03

You can use NSCalendar for components of a date.
If you want to format you date as you did, then please look into this doc for different date formatting string

// grab the selected data from the date picker
var chosenDate = self.datePicker.date
//use NSCalenda
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar?.components(.WeekdayCalendarUnit | .YearCalendarUnit, fromDate: chosenDate)
let weekDay = myComponents?.weekday
let year = myComponents?.year

println("year:\(year) , weekday:\(weekDay)")
查看更多
登录 后发表回答