2013-07-24 43 views
1

我接触过很多的计算器上的链接和试图执行代码,时间戳,这个格式转换2013-07-20T12:23:54.411 + 05:30这种格式的NSDate转换时间戳的NSDate不工作

2013年7月20日(星期二)12:23:54或1分钟前,2天前格式。

我已经实现了下面的代码。 toDate是零,即date1给出零价值。好像Xcode是针对此问题

我是说真的讽刺,你觉得这是什么操作的解释是: 与零TODATE?现在已经避免了一个例外。一些 这些错误将与此投诉进行报告,然后 进一步违规将简单地静静地做任何随机的事情 结果从零。

有谁能告诉我我哪里出了问题?

 NSDateFormatter *dateForm = [[NSDateFormatter alloc] init]; 
    [dateForm setDateFormat:@"yyyy-mm-ddTHH:mm:ssssZ"]; 
    [dateForm setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 
    [dateForm setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 
    [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
    NSDate *date1 = [dateForm dateFromString:string]; 
    NSDate *date2 = [NSDate date]; 
    unsigned int unitFlags = NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit; 

    // gets the difference between the current date and also the date and time in the timestamp of the data 
    NSDateComponents *diffComps = [cal components:unitFlags fromDate:date2 toDate:date1 options:0]; 

    int year = ABS([diffComps year]); 
    int month = ABS([diffComps month]); 
    int day = ABS([diffComps day]); 
    int hour = ABS([diffComps hour]); 
    int minute = ABS([diffComps minute]); 
    int seconds = ABS([diffComps second]); 
    NSString *displayTime; 

    if (year == 0) { 

     if (month == 0) { 

      if (day == 0) { 

       if (hour == 0){ 

        if (minute == 0) { 

         displayTime = [NSString stringWithFormat:@"about %d secs ago",seconds]; 
        } 
        else { 

         displayTime = [NSString stringWithFormat:@"about %d mins ago",minute]; 
        } 
       } 
       else { 

        displayTime = [NSString stringWithFormat:@"about %d hours ago",hour]; 
       } 
      } 
      else { 
       displayTime = [NSString stringWithFormat:@"about %d days ago",day]; 
      } 
     } 
     else { 

      displayTime = [NSString stringWithFormat:@"about %d months ago",month]; 
     } 
    } 
    else { 

     displayTime = [NSString stringWithFormat:@"about %d years ago",year]; 
    } 

编辑:这正常工作与我在AppDelegate中创建了一个字符串。但不是我在单例类中创建的字符串。

+0

“出错了”是什么? – trojanfoe

+0

检查编辑..... –

+0

您的日期格式错误。找到NSDateFormatter的文档,然后按照约6个链接的链来获取日期格式代码。答案就在那里。我会指出你的意思,但你不知道如何自己找到它。 (或者你可以搜索过去几十次之一,当问这个问题时)。 –

回答

2

您没有使用正确的时间格式;我会建议这样的:

yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ 
+1

对不起你的格式,但根据NSLog(@”%@“,[df stringFromDate:[df dateFromString:@”2013-07-20T12: 23:54.411 + 05:30“]]);'现在应该是正确的 –

+0

@MatthiasBauch没有问题,干杯 – trojanfoe

+0

只是再一次澄清,这段代码适用于一个字符串,而不是另一个具有相同格式时间...任何想法为什么? –