2013-10-08 97 views
0

我正在使用下面的代碼來計算monotouch中通知的時間戳。 dateAdded參數是DateTime作爲notificationDatetime來自服務器,格式爲UTC格式。 但「時間」即TimeSpan is getting negative sometimes because dateAdded value is getting greater than DateTime.UtcNow`,這是錯誤的。那麼,如何在monotouch中解決這個問題。DateTime releated issue in ios/monotouch

代碼:

public static string GetTimeStamp (this DateTime dateAdded) { 
    TimeSpan time = DateTime.UtcNow - dateAdded; 

    if (time.TotalDays > 7) 
     return string.Format ("on {0}", dateAdded.ToLocalTime().ToString ("MMM dd, yyyy 'at' hh:mm tt")); 
    if (time.TotalHours > 24) 
     return string.Format ("about {0} day{1} ago", time.Days, time.Days == 1 ? "" : "s"); 
    if (time.TotalMinutes > 60) 
     return string.Format ("about {0} hour{1} ago", time.Hours, time.Hours == 1 ? "" : "s"); 
    if (time.TotalSeconds > 60) 
     return string.Format ("about {0} minute{1} ago", time.Minutes, time.Minutes == 1 ? "" : "s"); 
    else if (time.TotalSeconds > 10) 
     return string.Format ("about {0} second{1} ago", time.Seconds, time.Seconds == 1 ? "" : "s"); 
    else 
     return "a moment ago"; 
} 
+2

「_dateadded值變得比DateTime.UtcNow大,這是錯誤的_」 - 我會先解決這個問題。 – neilco

回答

0

這裏有一些東西來檢查。

  1. DateTime.UtcNow正確的設備?
  2. 是真的用UTC添加的嗎?
  3. 是你的服務器日期和時間正確嗎?
  4. dateAdded.Kind == DateTimeKind.Utc

我檢查了執行DateTime.Subtract()-操作的,所以(4)不應該有任何影響,因爲它符合specification

減法(日期時間,日期)方法執行在執行 減法時,不考慮兩個日期時間值的Kind屬性值 。 [...]

所以我懷疑混合(2)和(3)。

+0

如何檢查設備上? 1)是否在設備上的DateTime.UtcNow正確? –

+0

'Console.WriteLine(DateTime.UtcNow);' –