【问题标题】:Objective-C date formatting from core data来自核心数据的 Objective-C 日期格式
【发布时间】:2012-10-19 15:20:14
【问题描述】:

我的核心数据实体有一个日期字段,我可以将其输出到 UITableViewCell,它的输出如下:

我想做的是更改此日期格式,使其更具人类可读性,例如到

10 月 19 日星期五 14:44

19/10/2012 14:44

如何在 Objective-C 中做到这一点?我想 NSDate 有一个格式化程序类,但是如何将提取的核心数据字符串转换为 NSDate?

【问题讨论】:

  • NSDateFormatter...。另外,如果核心数据实体可以具有 NSDate 属性,为什么要将日期存储为字符串?
  • 你是对的——我没有意识到这一点。我已更改为 NSDate,所以现在只需要知道如何格式化它,这样在屏幕上会更好一些。

标签: ios


【解决方案1】:

上述答案均无效,即使我尝试将核心数据对象转换为 NSDate,它仍然不会执行转换。我最终这样做了:

// Make a date formatter which corresponds exactly with the format of the date in core data
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];

// Get the date from core data
NSString *dateStr = [[object valueForKey:@"date"] description];

// Parse from string to date
NSDate *date = [dateFormatter dateFromString:dateStr ];

// Set the date formatter to the format that I actually want
[dateFormatter setDateFormat:@"dd/MM/yy HH:mm"];

// Set the text on the date label
cell.dateLabel.text = [dateFormatter stringFromDate:date];

【讨论】:

    【解决方案2】:

    试试这个方法:

    它可能需要根据语言环境进行调整,我没有测试过它,因为我没有能够和我一起编译代码的机器。

    - (NSString *)dateAsString:(NSDate *)theDate {
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateStyle:NSDateFormatterLongStyle]; 
    [df setTimeStyle:NSDateFormatterNoStyle];
    
    return  [df stringFromDate:theDate];
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多