Reputation: 4275
I have a UIDatePicker wich needs to gets validated. I want to check if the weekday from the UIDatePicker is a specific int value.
I use
@IBAction func validateDateTime(sender: AnyObject) {
var date = self.dateTime.date
let formatterWeekday = NSDateFormatter()
formatterWeekday.dateFormat = "e"
let weekday_string = formatterWeekday.stringFromDate(date)
}
to get the weekday but how can I convert it to an int so I can compare it with other int values? I tried it with:
weekday_string.intValue()
but it seems to be that weekday_string is not supporting the intValue method.
Upvotes: 1
Views: 1966
Reputation: 92422
I'm not fluent enough with Swift yet, so here's an answer in Objective-C instead. Since you already have the date, you don't need to fiddle with any formatters. You just need to ask the calendar for the components:
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate:date];
// components.weekDay is a number, representing the day of the week.
See the NSCalendar documentation and the NSDateComponents documentation.
To make it more stable, it's often a good idea to use a specific calendar instead of the current default calendar (users in different regions might use a non-Gregorian calendar). So instead of [NSCalendar currentCalendar]
, you'd use [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
.
Upvotes: 0
Reputation: 8066
stringFromDate
returns a string
. The method to convert string
to int
in Swift is toInt()
You can try:
weekday_string.toInt()
Or you can get the weekday as int
as follow:
var myDate = self.dateTime.date
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar.components(.WeekdayCalendarUnit, fromDate: myDate)
let weekDay = myComponents.weekday
Upvotes: 2