【问题标题】:Converting date format转换日期格式
【发布时间】:2017-12-23 05:48:31
【问题描述】:

我有这样的日期格式.. 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 值。我怎样才能得到这个?

【问题讨论】:

  • 您的转换出了什么问题。当你说你在几个小时和上午/下午都没有正确的时候,你得到了什么价值?
  • 我将小时:分钟值设为 10:51 而不是 15:51
  • 尝试使用 HH 代替 hh
  • 这是一个时区问题。您作为输入获得的日期是 UTC - 7 时区,您正在尝试转换为本地时区并打印。所以在你的格式中产生了问题。
  • 您可以在unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns ZZZ 上查看有效输入,例如“-0700” ZZZZ 例如"GMT-07:00" 但是你的输入是 "07:00" 你可以从服务器更改你的输入字符串并从时区中删除 ":" 吗?

标签: ios objective-c nsstring nsdate nsdateformatter


【解决方案1】:

需要如下设置日历区域:

-(NSString *)DateToString:(NSString *)getString
{

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
    NSDate *date = [format dateFromString:getString];
    [format setDateFormat:@"yyyy-MM-dd hh:mm a"];
    [format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    NSString* finalDateString = [format stringFromDate:date];
    return finalDateString;
}

【讨论】:

  • 这是正确答案,@Boobalan 为什么它没有按您的预期工作?
  • 以上代码适用于这种格式 .."2016-11-28T14:57:30.000Z" 而不是这种.."2017-06-05T15:51:56.996-07:00 "
【解决方案2】:
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

【讨论】:

  • 对不起,这根本行不通。将输入时间更改为@"2017-06-05T15:51:56.996-08:00"(时区偏移更改),它会产生相同的最终结果。导致dateWithTZ 的第二个代码块也不会用于确定finalDateString。
猜你喜欢
  • 2020-11-24
  • 2018-02-12
  • 1970-01-01
  • 2018-01-15
相关资源
最近更新 更多