Reputation:
I have put a button to save the current Date and Time to My Firebase Database .
private void saveTime() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child(Uid).child("time").setValue(ServerValue.TIMESTAMP);
}
I am trying to compare the server Date with My saved Date which i putted in my database . So please help me to compare it.
private void Compare() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ezzeearnRef = rootRef.child(Uid).child("time");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Long time = dataSnapshot.getValue(Long.class);
assert time != null;
Date oldDate = new Date(time);
GregorianCalendar oldCalendar = new GregorianCalendar();
oldCalendar.setTime(oldDate);
GregorianCalendar newCalendar = new GregorianCalendar();
Map<String, String> now = ServerValue.TIMESTAMP;
newCalendar.setTime((Date) now);
if (newCalendar.get(Calendar.DATE) != oldCalendar.get(Calendar.DATE) ||
newCalendar.get(Calendar.MONTH) != oldCalendar.get(Calendar.MONTH) ||
newCalendar.get(Calendar.YEAR) != oldCalendar.get(Calendar.YEAR)
) {
// new day starts toast
}
}else{
// toast
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
ezzeearnRef.addValueEventListener(eventListener);
}
Upvotes: 2
Views: 2815
Reputation: 18592
ServerValue.TIMESTAMP
is not really timestamp it a Map
so you cannot cast it to date like this
Map<String, String> now = ServerValue.TIMESTAMP;
newCalendar.setTime((Date) now);
the timestamp value will be stored from the server
Upvotes: 2
Reputation: 138824
You are correctly retrieving the timestamp from your database. To compare that timestamp, which is the server timestamp, with the accualt time, you can comparate with the current using the following line of code:
Long currentTimeMillis = System.currentTimeMillis();
Then you can use a simple if statement:
if(time < currentTimeMillis) {
//Do something
} else {
//Do something else
}
Upvotes: 0