我对UTC日期时间有问题。我有现有的安卓应用程序在Xamarin.android中,有时我会得到错误的日期和时间。我用C#生成协调世界时的时间
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。请给我一些建议
发布于 2021-05-18 13:29: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
}
}
发布于 2021-05-18 14:10:44
将datetime转换为字符串以存储在SQLite中,如下所示
string dateTimeInstring = DateTime.UtcNow.ToString();
并将从SQLite检索的datetime转换回DateTime,如下所示
DateTime utcDateTime = Convert.ToDateTime(dateTimeInstring);
DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
https://stackoverflow.com/questions/67587038
复制