How to Save the Current Date/Time When I Add New Value to Firebase Realtime Database

How to save the current date/time when I add new value to Firebase Realtime Database

I need to add current date to firebase Realtime database with other data and retrieve all data with date in kotlin android

If you want to add a Timestamp type field inside an object of type Notifications, then please define the following field in your class:

data class Notifications(
val emailA: String? = null,
val title: String? = null,
val body: String? = null,
val timestamp: Map<String, String>? = null
)

As you can see, the new field is of type Map<String, String>. Also remember, when you set the TIMESTAMP, you set it as a Map, but when you retrieve it, you retrieve it as a Long. Now, when you create an object, pass for the fourth argument ServerValue.TIMESTAMP).

Alternatively, you can create a Map and use:

map.put("timestamp", ServerValue.TIMESTAMP);

Save date in Firebase Realtime Database

You can parse the selected date like this and get the epoch milliseconds

val parsedDate = LocalDate.parse("your-date-here", dateFormatter)
val milliseconds = parseDate.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli()

you can then save the milliseconds to database. atStartOfDay() will set the time to midnight.

How to store data in Firebase Real-time Database under different date

Since you start with:

String dateString = DateTime.now().toString();

Any time this code runs, it determines the current date. So if you run the code on June 3, it will generate that date, and the key in your database will be for June 3.


Unrelated to your actual question, but I strongly recommend using ISO-8601 format for the dates, which would be: "2021-06-02". The advantage of this format, is that you can query for date ranges, for example getting all dates in 2021 with ref.orderByKey().startAt("2021-").endAt("2021~").

How to get firebase record between two particular dates?

Your "date" property is stored in the database as a String. This means that when you call "orderByChild("date")" the results will be ordered lexicographically. This means that Strings don't consider any sort of numeric values when sorting, especially when it comes to the dates, even if the dates contain numbers "23-4-2021". So you cannot use String values when querying your database:

.startAt(previousDate).endAt(currentDate)

Instead of Timestamp objects and expect to behave as it was a date. To solve this, you should change the type of your "date" property in the database to be of type Timestamp, and add it accordingly in the database as explained in my answer from the following post:

  • How to save the current date/time when I add new value to Firebase Realtime Database

Once you do that change, your code might remain unchanged and you'll get the desired results.



Related Topics



Leave a reply



Submit