【问题标题】:How do I NSLog an NSDate?我如何 NSLog 一个 NSDate?
【发布时间】:2013-08-29 21:34:14
【问题描述】:

使用下面粘贴的代码,我正在尝试记录 NSDate。我在这里做错了什么?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSDate *todaysDate;
todaysDate = [NSDate date];
NSLog(@"Todays date is %@",formatter);

【问题讨论】:

  • NSLog(@"The date is %@", todaysDate); -- 当然日期将以长格式和UTC时区记录,所以你需要了解这一点。要使用格式化程序,您可以使用NSLog(@"The date is %@", [formatter stringFromDate:todaysDate]);
  • 不相关但使用 yyyy 表示年份而不是 YYYY。详情请见stackoverflow.com/questions/3063068/…

标签: ios objective-c


【解决方案1】:

你所要做的就是:

  NSLog(@"Todays date is %@",[formatter stringFromDate:todaysDate]);

【讨论】:

    【解决方案2】:

    你做错了什么是你没有做任何事情来将日期与格式化程序相关联。所以,你会想做这样的事情:

    NSLog(@"Todays date is %@", [formatter stringFromDate:todaysDate];
    

    NSDate 对格式化一无所知(只是日期信息),NSDateFormatter 对日期一无所知,只知道如何格式化它们。因此,您必须使用 -stringFromDate: 之类的方法来实际格式化日期,以实现漂亮的人类可读显示。

    如果您只需要查看日期信息而不需要特定格式,则不需要格式化程序来记录日期:

    NSLog(@"Todays date is %@", todaysDate);
    

    可以很好地为您提供NSDate 对象的-description。我不会将它用于您向用户显示的任何内容(请为此使用 NSDateFormatter),但如果您只是在调试并且需要查看有关 NSDate 对象的信息,这将非常方便。

    【讨论】:

      【解决方案3】:

      完整示例:

          NSDate *today = [NSDate date];
          NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
          [formatter setDateFormat:@"YYYY-MM-dd"];
          NSLog(@"%@",[formatter stringFromDate:today]);
          [formatter release];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-30
        • 2011-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多