0

I have initialized a real time database using firebase, I am detecting live changes to the databse using

const ref = firebase.database().ref("test");

ref.on('value', function(dataSnapshot){
    console.log(dataSnapshot.val())
});

But this returns me value in ascending order. Whereas I want it to return based on time. I tried using time in: 00:00 (IST) format but if a data is marked 11:59 (am) and another 01:02 (pm) this will return me the second message first.

What will be the best way to fix this?

example data is => enter image description here

in my databse => enter image description here

Utkarsh Tyagi
  • 1,379
  • 1
  • 7
  • 12
  • "I tried using time" => What do you exactly mean?. We don't see any time field in the different messages in your DB. How can you sort on time, then? – Renaud Tarnec Jun 21 '21 at 08:27
  • In the database you see those childs - "akshat", "utkarsh", "zain" I replace them with IST i didn't show it cause I thought it was understandable, sorry my bad.. – Utkarsh Tyagi Jun 21 '21 at 11:08

1 Answers1

1

It is not clear what you mean by time in ascending order

None of your example data mention time. They are just usernames and text.

If you want to order times correctly, best to use ISO date format

This stores 1:02 pm as 13:02, which will sort after 11:59. Its sorting characteristics are ideal.

Use an international time standard to store your times

An international time standard, UTC, has great advantages over national times. It is not subject to change with location, political decisions, or season. You can always interconvert with the user's local time, at the time of entry or display.

Example

const dateString = (new Date()).toISOString();

console.log(dateString)
// Result: 
// 2021-06-22T14:40:37.985Z



// If you want to use them as Firebase keys, they must not contain a ".", so you might clean it up like this:

const cleanDateString = (new Date()).toISOString().replace(".","-")

console.log(cleanDateString)
// Result: 
// 2021-06-22T14:47:44-445Z

Even better, use a Firebase PushID

The above date-and-time system will work if you are using it to sort the remarks made by a single person, but will not be good as a message identifier if a single space is shared by all people, since 2 people will eventually make a message at the same millisecond, and will get the same message ID.

To deal with that it is better practice to use a Firebase Push ID.

An explanation is given here: In Firebase when using push() How do I get the unique ID and store in my database

Or from Firebase itself, here: https://firebase.google.com/docs/database/admin/save-data

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • 1
    thanks, i guess using ISO will probably fix my issue, one more favor in your answer can you please add how to get ISO time using javascript? – Utkarsh Tyagi Jun 21 '21 at 11:10