1

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.

Kingalione
  • 4,237
  • 6
  • 49
  • 84

2 Answers2

2

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
Jérôme
  • 8,016
  • 4
  • 29
  • 35
  • 1
    @Kingalione: I suggest you use the second approach Jerome posted instead, it's less overhead: parsing a date, turning it into a string and then turning the string into an integer is pretty expensive. – DarkDust Feb 18 '15 at 16:23
0

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].

DarkDust
  • 90,870
  • 19
  • 190
  • 224