Home >Java >javaTutorial >How to Efficiently Store and Retrieve Timestamps in Firebase Realtime Database?
When adding new data to a Firebase Realtime Database via the control panel, users often need to include the current date and time. This data can be useful for tracking user activity, managing logs, or sorting and filtering entries.
The recommended approach is to store the current date and time as a TIMESTAMP. Firebase offers a ServerValue.TIMESTAMP constant that automatically generates a server-side timestamp when used as a child value during a write operation.
To include the TIMESTAMP in your data using Java, use the following code:
To retrieve the TIMESTAMP as a Long in Java, use the following code:
In your model class, the timestamp field should be represented as:
Remember, when using ServerValue.TIMESTAMP, the timestamp only appears in the database after the write operation completes.
Another approach to obtaining the current timestamp is to use Cloud Functions for Firebase. This can be done with the following code:
Hosting this function in the cloud allows you to obtain the server timestamp without user interaction.
The above is the detailed content of How to Efficiently Store and Retrieve Timestamps in Firebase Realtime Database?. For more information, please follow other related articles on the PHP Chinese website!