【问题标题】:DateTime releated issue in ios/monotouchios/monotouch 中的日期时间相关问题
【发布时间】:2013-10-08 16:57:42
【问题描述】:

我正在使用下面的代码来计算单点触控通知的时间戳。 dateAdded 参数是来自服务器的DateTime,作为notificationDatetime,格式为UTC。 但是“时间”,即 TimeSpanis getting negative sometimes becausedateAddedvalue is getting greater thanDateTime.UtcNow`,这是错误的。那么,如何在 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";
}

【问题讨论】:

  • "date added value 越来越大于 DateTime.UtcNow,这是错误的"——我会先解决这个问题。

标签: ios xamarin.ios


【解决方案1】:

这里有几件事要检查。

  1. DateTime.UtcNow 在设备上是否正确?
  2. dateAdded 真的是 UTC 吗?
  3. 您的服务器日期和时间是否正确?
  4. dateAdded.Kind == DateTimeKind.Utc

我检查了DateTime.Subtract()- 运算符的实现,所以(4)不应该有任何影响,因为它符合specification

Subtraction(DateTime, DateTime) 方法不考虑值 执行时两个 DateTime 值的 Kind 属性的 减法。 [...]

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

【讨论】:

  • 如何在设备上查看? 1)设备上的 DateTime.UtcNow 是否正确?
  • Console.WriteLine (DateTime.UtcNow);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
相关资源
最近更新 更多