【问题标题】:How to get only date from ISO8601 timestamp to as string ios?如何仅将日期从 ISO8601 时间戳获取为字符串 ios?
【发布时间】:2016-01-13 06:03:37
【问题描述】:

您好,我以 ISO8601 的日期格式为例:

NSString *currentDateString = @"2016-01-12T21:21:22.737+05:30";

我只想从此字符串中获取 2016-01-12 的日期:

我试过了

[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(@"CurrentDate:%@", currentDate);

它重新调整为空,但我想以 yyyy-MM-dd 的格式获取日期。

【问题讨论】:

  • 日期格式化程序上的格式字符串需要与您要转换的字符串匹配。由于您的字符串比yyyy-MM-dd 多很多,因此日期格式化程序无法解析它。

标签: objective-c datetime nsdate nsdateformatter ios9.1


【解决方案1】:

请试试这个代码。

NSString *dateString = @"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date = %@", date);

【讨论】:

  • 您的解决方案仍然打印日期 = 2013-04-18 08:49:58 +0000。这不是我正在寻找的解决方案。
  • 此解决方案已将字符串转换为 NSDate 格式,之后您可以更改为任何格式
  • 是的,转换为 NSDate 后,您可以像这样使用转换为您想要的字符串 NSDateFormatter *shotDateFormatter = [[NSDateFormatter alloc] init]; [shotDateFormatter setDateFormat:@"yyyy-MM-dd"];NSString *shotDateString = [shotDateFormatter stringFromDate:date];
  • Tom 你的答案返回 shotDateString (null)。
【解决方案2】:

使用 NSRange 找到了解决方案:

NSString *currentDateString = @"2016-01-12T21:21:22.737+05:30";
NSRange range = [currentDateString rangeOfString:@"T"];
NSString *newString = [currentDateString substringToIndex:range.location];
NSLog(@"%@",newString);

【讨论】:

  • 这不是一个正确的方法,因为它正在做一种字符串操作
  • 如果您知道任何最好的做法也可以接受。
  • 此解决方案存在严重问题(假设您将 newString 传递给问题中的日期格式化程序)。通过截断字符串,您将丢失原始字符串中指定的时区。这意味着日期格式化程序会将字符串视为本地时间,而不是原始字符串中指定的时区。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2022-09-28
  • 2012-07-10
  • 1970-01-01
相关资源
最近更新 更多