Pregunta

So I am trying to store a date in Firebase like this:

 var fb = new Firebase(FIREBASE_URL);
        var syncData = $firebase(fb);
        var date = new Date(2014, 0, 1);
        console.log(date);
        syncData.$child('date').$set(date);
        var dateInFirebase = syncData.$child('date');
        dateInFirebase.$on('loaded', function(){
            console.log(dateInFirebase.$value);
        });

The first date correctly logs 'Wed Jan 01 2014 00:00:00 GMT+0100 (CET)', however the second log is this: '2013-12-31T23:00:00.000Z' which is 1 day before that, is this some bug in firebase or am I missing something obvious? I haven't found any other questions on this so I'm inclined to think I did something wrong, I just don't know what.

EDIT: Okay now I'm totally confused, if I replace the dateconstructor with the empty constructor (today's date) he stores the date correctly..

¿Fue útil?

Solución

Store dates using getTime(). When your read them back and want to display to users, use new Date(/* getTime value here */), and they will display correctly in any time zone. Additionally, client clocks may be skewed, so you should use Firebase.ServerValue.TIMESTAMP instead of new Date().

Otros consejos

I figured out why Firebase does this, my system is on GMT+2 time and the new date(year, month, day) constructor constructs the date at midnight. Firebase however saves the date as a UTC date so 2 hours get subtracted from the date, which leads to every date being saved at 10PM the day before the intended date.

This is also why new Date() did work, because a date at the current hour with 2 hours subtracted still works.

A workaround for this is just setting every date at 12:00 PM instead of 12:00 AM. If anyone knows of any better workarounds, it would be appreciated.

This answer might only be relevant for languages where you have a method for this, but in C# I can do dateFromFireBase.ToLocalTime(). This assumes that the date is saved in the same time zone as you load it in, which is the case for me. This should be possible in javascript too.

Also date store like this

var cdate =  new Date(); //2016-06-14 11:34:53
        var current_date = cdate.getFullYear()+"-"+cdate.getDate()+"-"+cdate.getMonth()+" "+cdate.getHours() + ":" + cdate.getMinutes() + ":" + cdate.getSeconds();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top