How to format date and time in XAML in Xamarin application

71,166

Solution 1

Change your code to:

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

Solution 2

Make a custom IValueConverter implementation:

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
}

Then use it like that:

<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>

Solution 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>

Solution 4

Use the standard .NET Date Format specifiers.

To get

September 12, 2014 2:30 PM

use something like

MMMM d, yyyy h:mm tt
Share:
71,166
Narendra
Author by

Narendra

Updated on June 17, 2020

Comments

  • Narendra
    Narendra about 4 years

    I have a set up XAML code below.

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

    I want result like september 12,2014 2:30 PM.

  • Narendra
    Narendra almost 9 years
    Date is binding as expected but time is not , it only displays 2: 30 but not 2:30 PM where time is a TimeSpan
  • Jason
    Jason almost 9 years
    a TimeSpan represents an interval - it does not have a concept of AM/PM
  • User1
    User1 over 8 years
    Googled this and found my own answer. First two answers are useless but this one solves it. Good job me!
  • Admin
    Admin over 6 years
    I try your code, but getting invalid cast exception on the line, var datetime = (DateTime)value; For me receiving the date as a java timestamp: 1510822596449. Is your code working for fine for converting java timestamp to string date?
  • niico
    niico over 4 years
    Can you provide the XAML please
  • Xonshiz
    Xonshiz almost 4 years
    This saved me a lot of time. This should be accepted answer...
  • rudi Ladeon
    rudi Ladeon almost 4 years
    Me too, i tried your code then i got a invalid cast exception.