Search code examples
javascriptreact-nativerealm

React Native: How to save date in realm DB


My realm model is:

const itemsSchema = {
    name: 'items',
    properties: {
        key: 'int',
        business_id: 'int',
        item_id: 'int',
        item_name: 'string',
        item_price: 'float',
        datetime: 'date'
        // datetime: 'string'
    }
};

I want to save the current date every time user hits a save button and this is the code executed on save which saves the data if I make my model property datetime: 'string'

realm.write(() => {
    realm.create('items', {
        key: 0,
        business_id: QRData.business_id,
        item_id: QRData.item_id,
        item_name: QRData.item_name,
        item_price: QRData.item_price,
        datetime: new Date('2017-06-06 21:23:53')
    });
});

But if try to save it with model property set as date it throws this error:

Error: Value 'Invalid Date' not convertible to a number.


Solution

  • Instead of

    new Date('2017-06-06 21:23:53')
    

    you can instantiate Date with parameters, like

    new Date(2017, 6, 6, 21, 23, 53)
    

    Note that month starts from 0.