【问题标题】:How to find weekday from today's date using NSDate?如何使用 NSDate 从今天的日期查找工作日?
【发布时间】:2011-01-28 18:58:40
【问题描述】:

我知道我可以通过[NSDate date]; 找出今天的日期,但我如何才能知道今天是星期几,比如星期六、星期五等。

我知道%w可以在NSDateFormatter中使用,但不知道怎么用。

【问题讨论】:

  • @Suhaib 仅供参考!!该链接比这个问题更新。

标签: objective-c nsdate


【解决方案1】:
let today = Date()
let day = Calendar.current.dateComponents([.weekday], from: today).weekday
if ( day == 5)
    {
        yourText.text = "Thursday"
    }

【讨论】:

    【解决方案2】:

    如果有人对 Swift 解决方案感兴趣,请使用:

    import Foundation
    
    let weekday = NSCalendar.current.component(.weekday, from: Date())
    print(weekday) // => prints the weekday number 1-7 (Sunday through Saturday) 
    

    请参阅demo

    更新:已修复,可在 Swift 3 中使用

    【讨论】:

    • 工作日是一个巨大的#?!
    • @Suhaib 答案更新以匹配最新的 Swift 版本。感谢您提出问题。
    【解决方案3】:
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:[NSDate date]];
    return [comp weekday]; // 1 = Sunday, 2 = Monday, etc.
    

    如果您只需要没有其他组件的工作日,请参阅@HuguesBR 的回答(需要 iOS 8+)。

    NSInteger weekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday 
                                                       fromDate:[NSDate date]];
    

    (如果您没有得到正确答案,请检查您是否将NSCalendarUnit<b>Weekday</b> 与其他与周相关的组件(如NSCalendarUnit<i>WeekdayOrdinal</i> 等)打错了)


    斯威夫特 3:

    let weekday = Calendar.current.component(.weekday, from: Date())
    // 1 = Sunday, 2 = Monday, etc.
    

    【讨论】:

    • comp weekday 返回一个不真实的巨大数字。 . .
    • @coolcool1994 你可能会使用NSWeekCalendarUnit insted of NSWeekdayCalendarUnit
    • 在 iOS8 上使用 NSCalendarUnitWeekday 代替已被弃用的 NSWeekdayCalendarUnit。不过答案非常好。谢谢
    【解决方案4】:

    短版

    NSCalendarUnit dayOfTheWeek = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday fromDate:yourDate];
    

    【讨论】:

      【解决方案5】:

      这是适用于 iOS 8 的更新版本

      NSCalendar* currentCalendar = [NSCalendar currentCalendar];
      NSDateComponents* dateComponents = [currentCalendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
      return [dateComponents weekday];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多