Narendra
Narendra

Reputation: 1412

How to format date and time in XAML in Xamarin application

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.

Upvotes: 62

Views: 88672

Answers (4)

JKennedy
JKennedy

Reputation: 18827

Change your code to:

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

Upvotes: 184

Mini Titan
Mini Titan

Reputation: 431

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

Upvotes: 12

Daniel Luberda
Daniel Luberda

Reputation: 7454

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>

Upvotes: 13

Jason
Jason

Reputation: 89214

Use the standard .NET Date Format specifiers.

To get

September 12, 2014 2:30 PM

use something like

MMMM d, yyyy h:mm tt

Upvotes: 6

Related Questions