使用 C# 在 Xamarin.android 中获取错误的 UTC 日期时间 (1970-01-01)

问题描述

我对 UTC 日期时间有疑问。我在 Xamarin.android 中有现有的 Android 应用程序,有时我会收到错误的日期时间。我正在使用

在 C# 中生成 UTC 时间
  string myUtcTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH\\:mm\\:ss"); 

我将 myUtcTime 值作为字符串数据类型保存到 sqlite 数据库列中。然后从 sqlite 获取 utcTime 并将其以 JSON 正文发送到服务器。

  Wrong value is  1970-01-01 03:07:18.000 

我不知道为什么有时我会在服务器上收到 1970-01-01。请高人指教

解决方法

我的建议是您需要来回转换(保存到数据库时和根据您的设计检索时)。

见下面的示例代码;

 public class DatetimeToStringConverter : IValueConverter
 {

public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
    if (value == null)
        return string.Empty;

    var datetime = (DateTime)value;
    //put your custom formatting here
    return datetime.ToLocalTime().ToString("g");
}

public object ConvertBack(object value,System.Globalization.CultureInfo culture)
{
    //Write your custom implementation 
}
 }
,

将日期时间转换为字符串以存储在 SQLite 中,如下所示

string dateTimeInstring = DateTime.UtcNow.ToString();

并将从 SQLite 检索到的日期时间转换回日期时间,如下所示

DateTime utcDateTime = Convert.ToDateTime(dateTimeInstring);
DateTime.SpecifyKind(utcDateTime,DateTimeKind.Utc);