【问题标题】:Not able to get the day of the week to display [duplicate]无法显示星期几
【发布时间】:2012-11-08 02:38:13
【问题描述】:

可能重复:
How do I get the day of the week in Objective-C?

我有一个连接到 nsstring 的 uilabel。但是,我正在尝试将 nsstring 设置为星期几(星期一、星期二等)。但每次我运行它时,它什么也没给我。我有一种感觉,这是因为我没有从我的 nsdate 中获得价值。但是,我是 xcode 的新手,所以我真的不知道自己做错了什么。

-(void)viewDidLoad {
     NSDate *today = [[NSDate alloc] init];
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];

        // Get the weekday component of the current date
        NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
                                                           fromDate:today];

       NSString *dateString = weekdayComponents;
        _label.text = dateString;
}

【问题讨论】:

    标签: ios xcode date nsdate


    【解决方案1】:

    主要问题是您试图将 NSDateComponents 对象分配给 NSString 变量。

    @JShapiro 给出的答案很好。但如果你想使用NSDateComponents,你可以这样做:

    NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
    NSInteger weekday = [weekdayComponents weekday];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSArray *weekdayNames = [formatter weekdaySymbols];
    
    _label.text = weekdayNames[weekday];
    

    【讨论】:

      【解决方案2】:

      试试这个代码:

      -(void)viewDidLoad {
          NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
          [formatter setDateFormat:@"EEEE"];
          _label.text = [formatter stringFromDate:[NSDate date]];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 2018-09-13
        • 1970-01-01
        • 2020-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-10
        相关资源
        最近更新 更多