【问题标题】:Why I am getting default date value when i try to format the date?为什么我在尝试格式化日期时得到默认日期值?
【发布时间】:2013-11-22 08:13:35
【问题描述】:

我使用以下代码将日期格式化为“MM/dd/YYYY”之类的格式

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YYYY"];
NSString *dateString=[dateFormatter stringFromDate:[NSdate date]];

NSString *dbDate=@"08/03/2013";


NSDate *currentDate=[dateFormatter dateFromString:dateString];
NSDate *newDate=[dateFormatter dateFromString:dbDate];
NSLog(@"currentDate is %@",currentDate);
NSLog(@"newDate is %@",newDate);

但我得到如下控制台输出

当前日期为 2013-01-04 18:30:00 +0000

newDate 是 2013-01-04 18:30:00 +0000

但我期待如下输出

当前日期是 2013 年 11 月 22 日

newDate 是 08/03/2013

谁能纠正我的错误

提前致谢

【问题讨论】:

    标签: ios objective-c nsdate


    【解决方案1】:

    NSDate 的 NSLog 始终是这种格式:

    yyyy-MM-dd HH:mm:ss +timezone
    2012-12-23 18:30:00 +0000
    

    如果您想要11/22/2013 格式,则需要将日期转换为NSString 并记录该字符串。

    另外,你有几个错误,请使用这个代码:

    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *dateString=[dateFormatter stringFromDate:[NSDate date]];
    NSString *dbDate=@"08/03/2013";
    NSDate *currentDate=[dateFormatter dateFromString:dateString];
    NSDate *newDate=[dateFormatter dateFromString:dbDate];
    
    NSLog(@"currentDate is %@",[dateFormatter stringFromDate:currentDate]);
    NSLog(@"newDate is %@",[dateFormatter stringFromDate:newDate]);
    

    输出:

    currentDate is 11/22/2013
    newDate is 08/03/2013
    

    【讨论】:

    • 我明白了,但我仍然没有得到我期望的日期,我得到的只是日期 2013-01-04 而不是 2013-11-22
    • 因为你的YYY,使用yyyy
    • @surendher:请阅读 Zsolt 勋爵的回答,因为他说不需要在 date->string 之间转换 3-4 次。
    【解决方案2】:

    你需要格式化你想要显示的字符串:

    NSLog(@"currentDate is %@",[dateFormatter stringFromDate: currentDate]);
    


    您的日期格式应为:

    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    

    【讨论】:

      【解决方案3】:

      使用以下代码。无需将[NSDate date]转为字符串,再转回NSDate,再转回字符串输出。

      你也写了 YYY 而不是 yyyy

      NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
      [dateFormatter setDateFormat:@"MM/dd/yyyy"];
      
      NSString *dbDate=@"08/03/2013";
      
      NSDate *currentDate = [NSDate date];
      NSDate *newDate=[dateFormatter dateFromString:dbDate];
      NSLog(@"currentDate is %@",[dateFormatter stringFromDate:currentDate]);
      NSLog(@"newDate is %@",[dateFormatter stringFromDate:newDate]);
      

      【讨论】:

      • 喜欢你的话,因为不需要转换 date->string->date->string :) 但可能是他在不同的方法调用中使用它。他可能不会只有这 8 行奇怪的代码。
      • 是的,很可能他只是把它留在那里进行测试,尽管每个都足够了:)
      猜你喜欢
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2014-01-09
      • 2011-06-16
      • 2018-02-07
      • 2018-02-12
      相关资源
      最近更新 更多