使用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, Type targetType, object parameter, 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);

最新更新