【问题标题】:format NSString to NSDate将 NSString 格式化为 NSDate
【发布时间】:2011-12-07 18:14:38
【问题描述】:

我从 facebook 获取用户日期,看起来像

"birthday_date" = "03/04/1987" 我写了这段代码

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"dd/MM/YYYY"];
    NSDate *dateFromString = [dateFormatter dateFromString:birthDate];

    NSLog(@"dateformstring %@ ",dateFromString);
    [birthPicker setDate:dateFromString animated:YES];

和字符串 si 的结果日期:1988-12-25 23:00:00 +0000,我在选择器中选择了这个日期,我不知道这个日期在哪里:/

【问题讨论】:

    标签: iphone objective-c nsdate nsdateformatter


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      哎呀。正如蒂洛所说,使用“yyyy”。正如Apple docs中提到的:

      “一个常见的错误是使用 YYYY。yyyy 指定日历年,而 YYYY 指定年份(“一年中的一周”),用于 ISO 年-周日历。”

      【讨论】:

        【解决方案3】:

        为此做了一个 NSString 扩展。

        // Simple as this.   
        date = dateString.dateValue;
        

        感谢NSDataDetector,它可以识别很多格式。

        // Tested in GMT+1 (Hungary).
        @"2014-01-16" dateValue is <2014-01-16 11:00:00 +0000>
        @"2014.01.16" dateValue is <2014-01-16 11:00:00 +0000>
        @"2014/01/16" dateValue is <2014-01-16 11:00:00 +0000>
        @"2014 Jan 16" dateValue is <2014-01-16 11:00:00 +0000>
        @"2014 Jan 16th" dateValue is <2014-01-16 11:00:00 +0000>
        @"20140116" dateValue is <2014-01-16 11:00:00 +0000>
        @"01-16-2014" dateValue is <2014-01-16 11:00:00 +0000>
        @"01.16.2014" dateValue is <2014-01-16 11:00:00 +0000>
        @"01/16/2014" dateValue is <2014-01-16 11:00:00 +0000>
        @"16 January 2014" dateValue is <2014-01-16 11:00:00 +0000>
        @"01-16-2014 17:05:05" dateValue is <2014-01-16 16:05:05 +0000>
        @"01-16-2014 T 17:05:05 UTC" dateValue is <2014-01-16 17:05:05 +0000>
        @"17:05, 1 January 2014 (UTC)" dateValue is <2014-01-01 16:05:00 +0000>
        

        eppz!kit 的一部分,从 GitHub 获取类别 NSString+EPPZKit.h。

        【讨论】:

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