How to format date and time in XAML in Xamarin application

DatetimeXamarinxamarin.forms

Datetime Problem Overview


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.

Datetime Solutions


Solution 1 - Datetime

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

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

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

Use the standard .NET Date Format specifiers.

To get

> September 12, 2014 2:30 PM

use something like

MMMM d, yyyy h:mm tt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNarendraView Question on Stackoverflow
Solution 1 - DatetimeUser1View Answer on Stackoverflow
Solution 2 - DatetimeDaniel LuberdaView Answer on Stackoverflow
Solution 3 - DatetimeMini TitanView Answer on Stackoverflow
Solution 4 - DatetimeJasonView Answer on Stackoverflow