Search code examples
c#xamarin.formstype-conversionrealm

How to convert DatePicker's DateTime to Realm's DateTimeOffset in Xamarin.Forms?


I have a class that is inherited from RealmObject with the Birthday property, which I enter with DatePicker. But Realm only works with DateTimeOffset. How can I elegantly convert all this?

XAML

<DatePicker MinimumDate="01/01/1400"
                        MaximumDate="11/14/2019"
                        Date="{Binding Author.Birthday}" />

Class Author

    public class Author : RealmObject
{
    //[PrimaryKey]
    public string Id { get; set; } = Guid.NewGuid().ToString();
    public string Name { get; set; }
    public string PhotoPath { get; set; }
    [Ignored]
    public Image Photo { get; set; }
    public DateTimeOffset? Birthday { get; set; }
    public IList<Book> Books { get; }
    public bool IsFavorite { get; set; }
}

Solution

    1. Using a value converter with the help of this
    2. Convert DateTime to DateTimeOffset with the help of this
    3. And if you are using that picker to show data as well you need to implement ConvertBack method of value converter. Converting Offset to DateTime rather easy as returning : offset.DateTime

    For in depth DateTimeOffset : link