ios - 转换日期格式

标签 ios objective-c nsstring nsdate nsdateformatter

我有这样的日期格式.. 2017-06-05T15:51:56.996-07:00,我需要将其转换为yyyy-MM-dd hh:mm a。我正在使用以下代码。

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSDate *date = [format dateFromString:dateString];
[format setDateFormat:@"yyyy-MM-dd hh:mm a"];
NSString* finalDateString = [format stringFromDate:date];`

但是我无法获得正确的小时数和AM / PM值。我怎么能得到这个?

最佳答案

NSString *dateStringWithTZ = @"2017-06-05T15:51:56.996-07:00";

// Create date object using the timezone from the input string.
NSDateFormatter *dateFormatterWithTZ = [[NSDateFormatter alloc] init];
dateFormatterWithTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSDate *dateWithTZ = [dateFormatterWithTZ dateFromString:dateStringWithTZ];

// Cut off the timezone and create date object using GMT timezone.
NSString *dateStringWithoutTZ = [dateStringWithTZ substringWithRange:NSMakeRange(0, 23)];
NSDateFormatter *dateFormatterWithoutTZ = [[NSDateFormatter alloc] init];
dateFormatterWithoutTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
dateFormatterWithoutTZ.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *dateWithoutTZ = [dateFormatterWithoutTZ dateFromString:dateStringWithoutTZ];

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd hh:mm a"];
[format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
format.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSString* finalDateString = [format stringFromDate:dateWithoutTZ];

结果:2017-06-05 03:51 PM

关于ios - 转换日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45165432/

相关文章:

iphone - 出列的 UITableViewCell 在滚动之前布局不正确(使用自动布局)

ios - 将第三方库 ZXing 导入 Xcode

ios - 在 Objective-C 项目中导入 Swift 框架 - 错误 - 未知类型名称

ios - CustomCell 未反射(reflect)在 UITableView 中

ios - UIView 中的 Swift TableView 不显示数据

iOS 提供了一个之前介绍过的模态视图 Controller

iphone - 淡出不适合的文本标签字符串的结尾(而不是截断)

iphone - 没有透明部分的图像蒙版

IOS:验证字符串是否为空字符串

ios - GKSession:发送字符串数组