目标C - 将时间从12格式转换为24格式

时间:2016-08-30 10:54:18

标签: ios objective-c iphone nsdate nsdateformatter

我正在使用下面的代码将时间从12格式转换为24格式并且工作正常,但结果比3小时的实际时间少! 即:如果时间是“下午12:40”,我转换为24格式后会得到“09:40”。

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone systemTimeZone]];    
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:strDate4Convert];    
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];    
NSString *newTimeStr = [df stringFromDate:newDate];

提前致谢;

2 个答案:

答案 0 :(得分:2)

是的,请使用localtimezone

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"08/30/2016 12:40 am"]; // @"08/30/2016 12:40 pm"
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];

输出:

打印newTimeStr的说明: 08/30/2016 00:40:00

打印newTimeStr的说明: 08/30/2016 12:40:00

答案 1 :(得分:1)

尝试将timeZone设置为UTClocalTimeZone而不是systemTimeZone

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//Or [df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* newDate = [df dateFromString:@"12/02/2016 12:40 pm"];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *newTimeStr = [df stringFromDate:newDate];