从字符串转换时,NSDate返回nil

时间:2015-01-21 02:14:45

标签: ios objective-c nsdate

我想从日期字符串中获取时间。以下字符串应返回12:00 AM。

2010-08-24 00:00:00 +0000

但是使用以下代码,我的NSDate对象在到达log语句时返回nil。这是什么问题?谢谢!

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"h:mma"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

输出:日期:( null)

2 个答案:

答案 0 :(得分:1)

试试这个:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"YYYY-MM-dd hh:mm:ss ZZZZ"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

干杯!

在操场上测试:

enter image description here

答案 1 :(得分:0)

您可以使用以下过程从日期字符串中提取时间

1.以给定格式获取NSDate对象。

2.使用所需格式设置NSDateFormatter对象。

3.以所需格式获取日期字符串。

 - (BOOL)application:(UIApplication *)
application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    NSString *date = [self convertDate:@"2010-08-24 00:00:00 +0000"
                            fromFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"
                              toFormat:@"hh:mm a"];

    NSLog(@"DATE: %@", [date description]);

    return YES;
}


- (NSString *)convertDate:(NSString *)inDateString
             fromFormat:(NSString *)fromFormat
               toFormat:(NSString *)toFormat
{
    NSDateFormatter *dateFormatter = nil;
    NSString *outDateString = nil;
    NSDate *date = nil;

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:fromFormat];

    date = [dateFormatter dateFromString:inDateString];

    [dateFormatter setDateFormat:toFormat];
    outDateString = [dateFormatter stringFromDate:date];

    return outDateString;
}