Android : Get Current Date And Time From Firebase
Solution 1:
Since Firebase Introduced Callable Functions, you can easily use it in your app by creating a Callable Function in Firebase Cloud Functions.
in your index.js
, create a Function and make it return the current timestamp
exports.getTime = functions.https.onCall((data,context)=>{
returnDate.now()
})
then deploy it to Firebase Cloud Functions
then in your Android App add the Callable Functions dependency
implementation 'com.google.firebase:firebase-functions:16.1.0'
then call the function from your app like this, and make sure you are typing the same name of the function 'getTime' as in your Cloud Function
FirebaseFunctions.getInstance().getHttpsCallable("getTime")
.call().addOnSuccessListener(newOnSuccessListener<HttpsCallableResult>() {
@OverridepublicvoidonSuccess(HttpsCallableResult httpsCallableResult) {
longtimestamp= (long) httpsCallableResult.getData();
}
});
you can also make a Simple interface if you want to call this method in multiple classes
publicinterfaceOnGetServerTime {
voidonSuccess(long timestamp);
voidonFailed();
}
publicvoidgetServerTime(final OnGetServerTime onComplete) {
FirebaseFunctions.getInstance().getHttpsCallable("getTime")
.call()
.addOnCompleteListener(newOnCompleteListener<HttpsCallableResult>() {
@OverridepublicvoidonComplete(@NonNull Task<HttpsCallableResult> task) {
if (task.isSuccessful()) {
longtimestamp= (long) task.getResult().getData();
if (onComplete != null) {
onComplete.onSuccess(timestamp);
}
} else {
onComplete.onFailed();
}
}
});
}
Solution 2:
ServerValue.TIMESTAMP
is just a token that Firebase Realtime Database converts to a number on the server when it's used as a child value during write operation. The date only appears in the database after the write completes.
If you want that value, you can read it back out of the database at the location you wrote it. But you should understand that this requires two round trips with the database, first to write it, then again to read it. By the time you get the value back, it will no longer be a perfect representation of the current moment in time, as it represents the moment in time that the value was initially written.
Solution 3:
you can convert timestamp to date and time using java.util.Date. for example
Datedate=newDate(timestamp.getTime());
Post a Comment for "Android : Get Current Date And Time From Firebase"