NSDateFormatter dateFromString格式为' hh:mm a'返回零

时间:2016-01-19 11:46:00

标签: ios objective-c iphone nsdate nsdateformatter

我在iPhone应用程序中遇到了一个问题。

在我的应用中,我将时间字符串转换为日期

NSString *time = @"01:30 PM";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"hh:mm a"];
NSDate *date = [dateFormat dateFromString:time];

由于某种原因,date之后始终[dateFormat dateFromString:time]为零。

谁能告诉我我做错了什么?

感谢

3 个答案:

答案 0 :(得分:2)

我假设您的设备语言不是英语。在这种情况下,您需要设置日期格式化程序Locale。试试这段代码。

NSString *time = @"01:30 PM";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"hh:mm a"];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

答案 1 :(得分:1)

试试这个......

NSString *time = @"01:30 pm";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
[dateFormat setDateFormat:@"hh:mm a"];
dateFormat.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSDate *date = [dateFormat dateFromString:time];

NSLog(@"date %@",[dateFormat stringFromDate:date]);

答案 2 :(得分:0)

    NSString *dats1 = @"01:30:00 PM";
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init] ;
    [dateFormatter1 setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter1 setDateFormat:@"HH:mm:ss"];
    NSDate *date = [dateFormatter1 dateFromString:dats1];
    NSLog(@"date : %@", date);

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh:mm a"];
    NSLog(@"Current Date: %@", [formatter stringFromDate:date]);