Reputation: 41
Button with onClickListener to post the TIMESTAMP in child("Date")
users.child(user.getUid()).child("Date").setValue(ServerValue.TIMESTAMP);
It works fine.
My problem is when I try to retrieve in my APP on the phone, I'm getting the current time not the actual TIMESTAMP time .
users.child(user.getUid()).child("Date").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Date date=new Date();
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
sfd.format(new Date());
TimeSold.setText(String.valueOf(date));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
The TIMESTAMP is changing on Firebase and it should be different from user to other. On my App it just gives me the same current time for all users.
My Firebase
Upvotes: 2
Views: 10885
Reputation: 138824
My problem is when I try to retrieve in my APP on the phone, I'm getting the current time, not the actual TIMESTAMP time.
This is happening because inside the callback you are actually creating a new Date
object rather than getting it from the database. To solve this, please use the following method:
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
And the following lines of code to get the date from the database:
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long date = ds.getValue(Long.class);
Log.d(TAG, getTimeDate(date));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
users.child(user.getUid()).child("Date").addListenerForSingleValueEvent(valueEventListener);
Edit:
To use your formatted Date, please use the following method:
public static String getTimeDate(long timestamp){
try{
Date netDate = (new Date(timestamp));
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return sfd.format(netDate);
} catch(Exception e) {
return "date";
}
}
Upvotes: 4
Reputation: 350
If the timestamp is saved as a Long
value, put:
Date date = new Date(dataSnapshot.getValue(Long.class));
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
Locale.getDefault());
String text = sfd.format(date);
TimeSold.setText(text);
in the onDataChange
callback
Your solution is not working because you're passing the current date to the format, as you wrote down:
Date date = new Date()
By default it takes the local current time.
Upvotes: 1