简体   繁体   English

将NSString格式化为NSDate

[英]format NSString to NSDate

i take the user date from facebook , it look like 我从facebook获取用户日期,它看起来像

"birthday_date" = "03/04/1987" i wrote this code “ 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];

and the result date from string si : 1988-12-25 23:00:00 +0000 , i have this date selected in the picker , I do not know where did this date :/ 和结果日期从字符串si:1988-12-25 23:00:00 +0000,我在选择器中选择了此日期,我不知道此日期在哪里:/

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

oops. 哎呀。 As tilo said, use "yyyy." 正如tilo所说,请使用“ yyyy”。 As mentioned in the Apple docs : 苹果文档中所述

"A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar." “一个常见的错误是使用YYYY。yyyy指定日历年,而YYYY指定在ISO年周日历中使用的年份(“年的周”)。”

Made an NSString extension for that. 为此做了一个NSString扩展

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

Thanks to NSDataDetector , it recognizes a whole lot of format. 感谢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>

Part of eppz!kit , grab the category NSString+EPPZKit.h from GitHub. 作为eppz!kit的一部分 ,从GitHub获取类别NSString + EPPZKit.h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM