format NSString to NSDate

2019-06-11 09:17发布

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

3条回答
何必那么认真
2楼-- · 2019-06-11 09:49

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-11 09:55

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

查看更多
Deceive 欺骗
4楼-- · 2019-06-11 10:00

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

查看更多
登录 后发表回答