format NSString to NSDate

妖精的绣舞 提交于 2020-01-14 05:28:24

问题


i take the user date from facebook , it look like

"birthday_date" = "03/04/1987" i wrote this code

 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 :/


回答1:


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




回答2:


oops. As tilo said, use "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."




回答3:


Made an NSString extension for that.

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

Thanks to NSDataDetector, it recognizes a whole lot of format.

// 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.



来源:https://stackoverflow.com/questions/8420351/format-nsstring-to-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!