我有一個時間戳屬性,它是一種long型別,并且我已將其系結到一ListView列。使用 XAML,我試圖將此時間戳(long型別)轉換為日期和時間,具體取決于正在運行的機器的當前區域設定。
我想得到這樣的東西:
mm/dd/yyyy HH:mm或dd/mm/yyyy HH:mm(24 小時制)
要么
mm/dd/yyyy hh:mmPM 或dd/mm/yyyy hh:mmPM(12 小時制)
取決于機器區域設定。
所以我使用StringFormat:
<GridViewColumn Header="Id"
DisplayMemberBinding="{Binding Path=Timestamp, StringFormat='g'}"/>
但它似乎不起作用。在網格視圖單元格中,它顯示為一個long數字。
uj5u.com熱心網友回復:
是通用格式說明符g,它將顯示為數字。long
通用(“G”)格式說明符將數字轉換為更緊湊的定點或科學記數法,具體取決于數字的型別以及是否存在精度說明符。
日期格式化機制不能直接與long. ADateTime表示日期和時間是明確的,但是您如何long從哪里將 解釋為秒、毫秒?請參閱標準日期和時間格式字串的檔案。
標準日期和時間格式字串使用單個字符作為格式說明符來定義 a
DateTime或DateTimeOffset值的文本表示。
顯而易見的解決方案是通過型別屬性而DateTime不是long. 然后,您可以在 XAML 中使用標準和自定義日期格式說明符StringFormat。
public DateTime Timestamp { get; }
或者,您可以創建一個自定義值轉換器,將 轉換long為DateTime.
public class LongToDateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is long milliseconds))
return value;
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return dateTime.AddMilliseconds(milliseconds).ToLocalTime();
// Alternative in > .NET Core 2.1
//return DateTime.UnixEpoch.AddMilliseconds(milliseconds);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return new NotImplementedException();
}
}
在范圍內的任何資源中創建轉換器的實體,例如Window.Resources.
<Window.Resources>
<local:LongToDateConverter x:Key="LongToDateConverter"/>
</Window.Resources>
由于轉換發生在格式化之前,您可以保留StringFormat.
如果設定
Converter和StringFormat屬性,轉換器將首先應用于資料值,然后再StringFormat應用 。
<GridViewColumn Header="Id"
DisplayMemberBinding="{Binding Path=Timestamp, Converter={StaticResource LongToDateConverter}, StringFormat='g'}"/>
您可以參考自定義日期和時間格式字串來創建所需的格式字串。
StringFormat='MM/dd/yyyy HH:mm'
StringFormat='dd/MM/yyyy HH:mm'
StringFormat='MM/dd/yyyy hh:mm'
StringFormat='dd/MM/yyyy'
更新您的評論:
I forgot to say in my post (sorry) that this long timestamp was obtained by doing
DateTime.UtcNow.ToFileTimeUtc()[...]
I assumed the Unix timestamp. As you can see, a long is pretty ambiguous. In this case you can convert the long back as stated in the documentation.
The
ToFileTimeUtc()method is sometimes used to convert a local time to UTC, and subsequently to restore it by calling theFromFileTimeUtc(Int64)method followed by the ToLocalTime() method. However, if the original time represents an invalid time in the local time zone, the two local time values will not be equal.
The converter method would do exactly this.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is long milliseconds))
return value;
return DateTime.FromFileTimeUtc(milliseconds).ToLocalTime();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449077.html
