Wrong date format on Xamarin Forms, how to resolve?

Asked

Viewed 249 times

1

In my mobile application I have a part that I recover the local date and time, so the date is bringing first the month, then the day and for last year, how to change this, here is my code:

In my layout file:

<Label Text="Data" FontAttributes="Bold"/>
<Label Text="{Binding DataAtual}"/> 

Here the class created for the logical part:

public class DataHora : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private DateTime _dataAtual;
    public DateTime DataAtual
    {
        set
        {
            if (_dataAtual == value)
                return;

            _dataAtual = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DataAtual)));
        }
        get
        {
            return _dataAtual;
        }
    }

    public DataHora()
    {
        DataAtual = DateTime.Now;

        Device.StartTimer(TimeSpan.FromSeconds(1), () =>
        {
            DataAtual = DateTime.Now;
            return true;
        });
    }
}

And here in my mainpage file:

BindingContext = new DataHora();

1 answer

1


Binding supports setting the string format you want to present.

Just change the label binding in your XAML to the following:

<Label Text="{Binding DataAtual, StringFormat='{0:dd/MM/yyyy HH:mm:ss}'}"/>

If you only do the Binding cru, the default behavior is a ToString() in the object, and in this case, certainly it is following the format of the date defined in the culture of its emulator, most likely en-US;

  • 1

    Perfect, thank you very much! I just added also hh:mm:ss and got filet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.