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
![Narendra](https://i.stack.imgur.com/ZrvHU.jpg?s=256&g=1)
Author by
Narendra
Updated on June 17, 2020Comments
-
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 almost 9 yearsDate is binding as expected but time is not , it only displays 2: 30 but not 2:30 PM where time is a TimeSpan
-
Jason almost 9 yearsa TimeSpan represents an interval - it does not have a concept of AM/PM
-
User1 over 8 yearsGoogled this and found my own answer. First two answers are useless but this one solves it. Good job me!
-
Admin over 6 yearsI 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 over 4 yearsCan you provide the XAML please
-
Xonshiz almost 4 yearsThis saved me a lot of time. This should be accepted answer...
-
rudi Ladeon almost 4 yearsMe too, i tried your code then i got a invalid cast exception.