【问题标题】:Objective-C - Convert this format P18Y9M4DT11H9M8S do NSDATE [duplicate]Objective-C - 转换此格式 P18Y9M4DT11H9M8S 做 NSDATE [重复]
【发布时间】:2014-03-25 17:10:11
【问题描述】:

我需要将此日期格式@"P18Y9M4DT11H9M8S"(18 年、9 个月、4 天、11 小时、9 分钟和 8 秒)转换为 NSDate 我可以使用算法来做到这一点,但我认为有一种简单的方法可以做到这一点.

【问题讨论】:

  • 有关您从何处获得该格式的任何信息?
  • 作为网络服务的结果。
  • 这是一个"ISO 8601 Duration",描述了一个时间间隔的长度,而不是一个绝对的时间点。因此,将其转换为 NSTimeInterval 或 NSDateComponents 会更有意义......

标签: ios nsdate


【解决方案1】:

试试:

NSString *myDate = @"P18Y9M4DT11H9M8S";

myDate = [myDate stringByReplacingOccurrencesOfString:@"P" withString:@""];
myDate = [myDate stringByReplacingOccurrencesOfString:@"Y" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"M" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"D" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];
myDate = [myDate stringByReplacingOccurrencesOfString:@"H" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"S" withString:@""];

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy/MM/dd HH/mm/ss"];
NSDate *date = [f dateFromString:myDate];

NSLog(@"date = %@", date);

【讨论】:

    【解决方案2】:

    使用 NSDateformattet 并设置格式以及其他一些选项。然后调用 -dateFromString。有关更多详细信息,请参阅链接: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2013-03-27
      相关资源
      最近更新 更多