[英]Getting Wrong UTC date time (1970-01-01) in Xamarin.android using C#
我對 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 如下
DateTime utcDateTime = Convert.ToDateTime(dateTimeInstring);
DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.