How to format date and time in XAML in Xamarin application

前端 未结 4 2110
时光取名叫无心
时光取名叫无心 2020-12-08 13:52

I have a set up XAML code below.



相关标签:
4条回答
  • 2020-12-08 14:00
    <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>
    
    0 讨论(0)
  • 2020-12-08 14:05

    Use the standard .NET Date Format specifiers.

    To get

    September 12, 2014 2:30 PM

    use something like

    MMMM d, yyyy h:mm tt
    
    0 讨论(0)
  • 2020-12-08 14:13

    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>
    
    0 讨论(0)
  • 2020-12-08 14:15

    Change your code to:

    <Label Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"></Label>
    <Label Text="{Binding Time, StringFormat='{}{0:hh\\:mm}'}"></Label>
    
    0 讨论(0)
提交回复
热议问题