NSDateFormatter:dateFromString返回nil

时间:2016-04-15 13:40:55

标签: ios objective-c nsdate nsdateformatter

我的日期格式如下:

    NSString *dateString = @"1996-08-09T07:00:00Z";

我只需从上面的日期中提取年份:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormat setLocale:[NSLocale currentLocale]];
    [dateFormat setDateFormat:@"yyyy"];
    [dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];
    NSDate *date = [dateFormat dateFromString:dateString];
    NSLog(@"date : %@", date);

记录:

    2016-02-15 06:36:47.496 App[46714:5560483] date : (null)

我甚至尝试过:

    [dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]

但无济于事。

enter image description here

3 个答案:

答案 0 :(得分:1)

将日期格式设为

SELECT ID, Name, DOB, Address FROM customer c
LEFT JOIN full_customer fc ON c.ID = fc.ID
WHERE fc.ID IS NULL

<强>更新

                            1996-08-09T07:00:00Z
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

输出

enter image description here

答案 1 :(得分:0)

格式:

yyyy

与日期字符串不匹配:

1996-08-09T07:00:00Z

因此[NSDateFormatter dateFromString:]返回nil

您想要这种格式:

yyyy-MM-dd'T'HH:mm:ssZ

(注意X说明符是documented作为Z(祖鲁时间)的正确说明符,但在与@rmaddy的讨论中,他让我相信{{1}是正确使用的。)

然后使用Z提取年份。

答案 2 :(得分:0)

尝试此功能:

 +(NSDate *)convertUTCDateLocal:(NSString*)inputString
{
    NSString *dateFormat = @"yyyy-MM-dd'T'HH:mm:sszz";
    //for input
    NSTimeZone *inputTimeZone =[NSTimeZone timeZoneWithName:@"UTC"];
    NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
    [inputDateFormatter setTimeZone:inputTimeZone];

    //NSString *inputString = @"2015-07-31T14:00:00+0000";
    [inputDateFormatter setDateFormat:dateFormat];
    NSDate *date = [inputDateFormatter dateFromString:inputString];

    //for output
    NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
    [outputDateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [outputDateFormatter setLocale:[NSLocale currentLocale]];
    [outputDateFormatter setDateFormat: @"yyyy"];

    NSString *outputString = [outputDateFormatter stringFromDate:date];

    NSDate *outputDate = [outputDateFormatter dateFromString:outputString];

    return outputDate;
}