18

I'm new to Firebase and I was wondering how I can store a JavaScript date and use Firebase to compare them on the client side later?

I want to do something like:

var someDate = new Date();
myRootRef.set(someDate);

myRootRef.on('value', function(snapshot) {
     var currDate = new Date();
if (currDate >=  snapshot.val()){
     //do something
}

However, I get back a value of null from the snapshot?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
TriFu
  • 641
  • 3
  • 10
  • 19

2 Answers2

22

You can also use timestamp.

var timestamp = new Date().getTime();
myRootRef.set(timestamp);

myRootRef.on('value', function(snapshot) {
    var currDate = new Date();
    var snapshotTimestamp = snapshot.val();

    //you can operate on timestamps only...
    console.log("Snapshot timestamp: " + snapshotTimestamp);

    if(currDate.getTime() >= snapshotTimestamp) {
        //do something
    }

    //...or easily create date object with it  
    console.log("Snapshot full date: " + new Date(snapshotTimestamp));

    if (currDate >=  new Date(snapshotTimestamp)){
        //do something
    }

});
ghost
  • 769
  • 5
  • 11
  • 3
    Additionally, unless both dates are from the same client, you'll probably want to consult `.info/serverTimeOffset` and add that to the timestamp: `new Date().getTime() + offset`; otherwise you're going to get some weirdness for users who don't keep their clock synced within a second of atomic time – Kato May 05 '13 at 18:26
  • thanks for the replies and code samples! I really appreciate it! – TriFu May 05 '13 at 23:45
-3

You need to set a Firebase with string or object with value, and than read the same value in the event.

    var someDate = new Date();
    myRootRef.set({Date: someDate.toString()});

    myRootRef.on('value', function(snapshot) {
    var msg = snapshot.val();
     var currDate = new Date();
    if (currDate >=  msg.Date){
     //do something
    }
    });
Eyal
  • 110
  • 4
  • Comparing dates as strings won't achieve a correct date comparison, so you'll probably want to use the timestamp approach recommend by @ghost. – Michael Lehenbauer May 05 '13 at 15:47