iOS:Objective-C:ipad时间显示12小时/24小时导致的输出问题

iOS:Objective-C:ipad时间显示12小时/24小时导致的输出问题,ios,objective-c,nsdate,nsdateformatter,Ios,Objective C,Nsdate,Nsdateformatter,在我的应用程序中,我使用一个函数来更改日期格式,以替换/和日期格式 当设备设置为12小时时,一切正常。但当我将其设置为24小时时,它返回错误的值 NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]); //input date is : 6/6/2017 6:38:00 PM -(NSDate *)convertDateSlashToDash:(NSString *)d

在我的应用程序中,我使用一个函数来更改日期格式,以替换/和日期格式

当设备设置为12小时时,一切正常。但当我将其设置为24小时时,它返回错误的值

NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]);


//input date is  : 6/6/2017 6:38:00 PM
-(NSDate *)convertDateSlashToDash:(NSString *)dateStr{

if ([dateStr isKindOfClass:[NSDate class]]) {
    return (NSDate*)dateStr;
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];

// in ms 1469077819000 without ms 1469077819 for 7/21/2016 5:10:19 AM
NSTimeInterval ti = [[dateFormatter dateFromString:dateStr] timeIntervalSince1970];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:ti];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];

// [formatter setLocale:[NSLocale currentLocale]];

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
NSString *dateString = [formatter stringFromDate:date];
NSDate *parsedDate = [formatter dateFromString:dateString];

return dateString;
}
 //output of this is (24hrs): 1970-01-01 05:30:00AM

 //output of this is (12hrs): 2017-06-06 06:38:00 PM
为什么它不起作用? 请建议


谢谢。

12小时和24小时的指定与日期格式化程序不同。确保您使用的格式正确。我看到您使用h表示小时,最后使用a将格式化程序配置为12小时格式。对于24小时格式,您需要H或HH,具体取决于您的需要。您可以参考此内容以更好地了解不同的格式

请将此行添加到代码中以解决此问题

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

阅读更多信息:

您正在返回dateString?是的,我需要它是错误的值,我认为它是parsedDate,parsedDate和dateString返回相同的值。只有parsedDate是NSDate,dateString是NSStringyes,但在我的代码中,输入日期始终是12小时格式,我正在尝试转换该日期。