簡體   English   中英

在WPF中使用TextBlock中的StringFormat格式化日期

[英]Format date with StringFormat in TextBlock in WPF

我已將日期存儲在數據庫中,但由於某些原因未減。 這意味着我有一個日期字段,如20110602。

由於我想檢索此日期並將其顯示在文本塊中,因此我需要一種格式以將該日期顯示為帶斜杠的正常日期。

我如何以這種方式使用StringFormat? ...有人知道我應使用什么格式將“ 20110602”轉換為2011/06/02嗎?

<TextBlock  Text="{Binding CreatedDate, StringFormat=?????" 

如果您選擇實施轉換器的途徑:

class dateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string dateString = (string)value;
        return DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在你的xaml中

<TextBlock Text="{Binding Path=<path>, Converter={StaticResource <dateTimeConverterKey>}, StringFormat=\{0:yyyy/MM/dd\}}"/>

嘗試使用DateTime.ParseExact方法:

  dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
  format = "ddd dd MMM yyyy h:mm tt zzz";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }

在您的情況下,我認為格式應為:

 format = "yyyyMMdd";

有關更多信息: http : //msdn.microsoft.com/zh-cn/library/w2sa9yss.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM