【问题标题】:How to format date and time in XAML in Xamarin application如何在 Xamarin 应用程序中格式化 XAML 中的日期和时间
【发布时间】:2015-12-25 04:11:45
【问题描述】:

我在下面设置了 XAML 代码。

<Label Text="{Binding Date}"></Label>
<Label Text="{Binding Time}'}"></Label>

我想要 2014 年 9 月 12 日下午 2:30 这样的结果。

【问题讨论】:

  • 看起来你好像已经忘记添加你的 xaml 代码了!
  • 下面的答案可能更接近您正在寻找的答案,但您应该注意 Xamarin Forms 在绑定日期格式方面存在错误。 forums.xamarin.com/discussion/comment/290295/#Comment_290295
  • @MelbourneDeveloper 我看到了您的帖子,问题已移至 GitHub。非常感谢您的贡献。不幸的是,截至今天,仍然没有解决。我将在此处留下一个指向 GitHub-Issue 的链接,以便人们了解最新信息。 github.com/xamarin/Xamarin.Forms/issues/2049

标签: datetime xamarin xamarin.forms


【解决方案1】:

将您的代码更改为:

<Label Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"></Label>
<Label Text="{Binding Time, StringFormat='{}{0:hh\\:mm}'}"></Label>

【讨论】:

  • 谷歌搜索并找到了我自己的答案。前两个答案没用,但这个解决了它。干得好!
  • 这为我节省了很多时间。这应该被接受的答案...
【解决方案2】:

制作自定义 IValueConverter 实现:

public class DatetimeToStringConverter : IValueConverter
{
    #region IValueConverter implementation

    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)
    {
        throw new NotImplementedException(); 
    }

    #endregion
}

然后像这样使用它:

<ResourceDictionary>
    <local:DatetimeToStringConverter x:Key="cnvDateTimeConverter"></local:DatetimeToStringConverter>
</ResourceDictionary>

...

<Label Text="{Binding Date, Converter={StaticResource cnvDateTimeConverter}}"></Label>
<Label Text="{Binding Time, Converter={StaticResource cnvDateTimeConverter}}"></Label>

【讨论】:

  • 我尝试了您的代码,但是在线上出现了无效的强制转换异常,var datetime = (DateTime)value;对我来说,将日期作为 Java 时间戳接收:1510822596449。您的代码是否可以将 Java 时间戳转换为字符串日期?
  • 我也是,我试过你的代码然后我得到一个无效的强制转换异常。
【解决方案3】:
<Label>

<Label.FormattedText>

<FormattedString>

<Span Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"/>
<Span Text=" "/>
<Span Text="{Binding Time, StringFormat='{0:h:mm tt}'}"/>

</FormattedString>

</Label.FormattedText>

</Label>

【讨论】:

    【解决方案4】:

    使用标准的.NET Date Format 说明符。

    得到

    2014 年 9 月 12 日下午 2:30

    使用类似的东西

    MMMM d, yyyy h:mm tt
    

    【讨论】:

    • 日期按预期绑定,但 time 不是,它只显示 2:30 而不是下午 2:30,其中时间是 TimeSpan
    • 一个 TimeSpan 代表一个 间隔 - 它没有 AM/PM 的概念
    • 你能提供 XAML 吗
    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多