【问题标题】:Swift compare weekday of a date with a intSwift 将日期的工作日与 int 进行比较
【发布时间】:2015-02-18 16:00:09
【问题描述】:

我有一个需要验证的 UIDatePicker。我想检查 UIDatePicker 中的工作日是否是特定的 int 值。

我用

@IBAction func validateDateTime(sender: AnyObject) {
    var date = self.dateTime.date

    let formatterWeekday = NSDateFormatter()
    formatterWeekday.dateFormat = "e"

    let weekday_string = formatterWeekday.stringFromDate(date)

}

要获得工作日,但如何将其转换为 int 以便与其他 int 值进行比较?我试过了:

weekday_string.intValue() 

但似乎是weekday_string不支持intValue方法。

【问题讨论】:

  • 我也试过了,但我不知道如何快速编写这段代码。我对使用 os 进行编码非常陌生...
  • Jerome 的回答告诉你如何用 swift 写这个。

标签: swift nsdate nsdateformatter


【解决方案1】:

stringFromDate 返回一个string。 Swift中将string转换为int的方法是toInt()

你可以试试:

weekday_string.toInt()

或者您可以通过int 获取工作日,如下所示:

var myDate = self.dateTime.date
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar.components(.WeekdayCalendarUnit, fromDate: myDate)
let weekDay = myComponents.weekday

【讨论】:

  • @Kingalione:我建议您使用 Jerome 发布的第二种方法,它的开销较小:解析日期,将其转换为字符串,然后将字符串转换为整数非常昂贵。
【解决方案2】:

我对 Swift 还不够流利,所以这里有一个 Objective-C 的答案。由于您已经有了日期,因此您不需要摆弄任何格式化程序。您只需要向日历询问组件:

NSDateComponents *components = [[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate:date];
// components.weekDay is a number, representing the day of the week.

请参阅NSCalendar documentationNSDateComponents documentation

为了使其更加稳定,使用特定日历而不是当前默认日历通常是个好主意(不同地区的用户可能使用非公历)。所以你可以使用[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar],而不是[NSCalendar currentCalendar]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多