【问题标题】:Date with Month name Objective-C带有月份名称的日期 Objective-C
【发布时间】:2011-09-08 11:48:55
【问题描述】:

我有一个NSDate 对象,其值为例如:“2011-08-26 14:14:51”,我想显示“2011 年 8 月 8 日”如何实现?谢谢。

【问题讨论】:

标签: objective-c nsdate nsdateformatter


【解决方案1】:
NSDate *date = [NSDate date]; //I'm using this just to show the this is how you convert a date

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterLongStyle]; // day, Full month and year
[df setTimeStyle:NSDateFormatterNoStyle];  // nothing

NSString *dateString = [df stringFromDate:date]; [df release];

【讨论】:

  • 这个方法不起作用.. [df setDateFormat:NSDateFormatterLongStyle]; - 错误在这里 - [df setTimeFormate:NSDateFormatterNoStyle];
  • @mazder - 抱歉 - 这次我已经编辑过了。再试一次。
  • 谢谢,现在可以了。但是当我尝试从字符串中获取日期时,它显示January 26, 2011 为什么?
  • 因为 Mayur Joshi 给出的格式是错误的。它应该是 @"YYYY-MM-dd HH:mm:ss" 因为使用 D 表示一年中的几天 1..365,而不是使用 dd 的月份中的几天
【解决方案2】:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"dd LLLL yyyy"];
NSString *formattedDate = [df stringFromDate:[NSDate date]];

【讨论】:

    【解决方案3】:
    NSString *dateStr = @"2011-08-26 14:14:51";
    
    //if you have date then, 
    NSString *dateStr = [NSString stringWithFormat:@"%@",yourDate];
    
    
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    [dateFormat setDateFormat:@"MMMM dd, YYYY"];
    NSString* temp = [dateFormat stringFromDate:date];
    
    [dateFormat release];
    
    
    
    NSLog(@"%@",temp);
    

    【讨论】:

    • 您的日期格式字符串错误。它应该是@"YYYY-MM-dd HH:mm:ss"。 D 表示一年中的天数 d 表示月份中的天数
    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2017-09-09
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多