【问题标题】:NSDateFormatter not converting NSString properlyNSDateFormatter 没有正确转换 NSString
【发布时间】:2012-06-12 12:56:34
【问题描述】:

试图证明我可以将NSString 转换为NSDate 的简单案例。创建一个NSDate,将其转换为NSString,然后再转换为NSDate。日期作为字符串看起来不错,但是当我将其转换回来时,我总是会得到一些日期,例如 12/25/2011 .... 有人能发现我的错误吗?

 NSDateFormatter *df = [[NSDateFormatter alloc] init];
 [df setDateFormat:@"dd/MM/YY hh:mm a"];
 NSDate* b = [[NSDate alloc] init];
 NSString* f = [df stringFromDate:b]; // has the current date and time
 NSDate* dt =[df dateFromString:f];  // 12/25/2011 - where does it get this?

【问题讨论】:

    标签: ios ios5 nsdate nsdateformatter


    【解决方案1】:

    尝试使用以下内容:

    [df setDateFormat:@"dd/MM/yyyy hh:mma"]; // or @"dd/MM/yy hh:mma"
    

    这是结果:

    Printing description of b:
    2012-06-12 13:06:16 +0000
    Printing description of dt:
    2012-06-12 13:06:00 +0000
    

    如果您需要更多信息,我建议您阅读date-formatter-examples

    如果您不使用 ARC,请注意内存泄漏。例如,使用[NSDate date] 而不是[[NSDate alloc] init]

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      对我来说,您的系统似乎正在使用 Datestyle。

      您是否应该将格式化程序设置为不使用样式:

      [df setDateStyle:NSDateFormatterNoStyle];

      为什么你一般不使用这种风格?看来NSDateFormatterShortStyle 是您想要的。您只需同时设置时间样式并使用setLocal: 将日期按您想要的顺序显示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多