2013-07-24 41 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

只是再一次澄清,這段代碼適用於一個字符串,而不是另一個具有相同格式時間...任何想法爲什麼? –