Android:Get Current Date and Time from Firebase

Android : Get current date and time from firebase

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)=>{
return Date.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(new OnSuccessListener<HttpsCallableResult>() {
@Override
public void onSuccess(HttpsCallableResult httpsCallableResult) {
long timestamp = (long) httpsCallableResult.getData();

}
});

you can also make a Simple interface if you want to call this method in multiple classes

public interface OnGetServerTime {
void onSuccess(long timestamp);

void onFailed();
}

public void getServerTime(final OnGetServerTime onComplete) {
FirebaseFunctions.getInstance().getHttpsCallable("getTime")
.call()
.addOnCompleteListener(new OnCompleteListener<HttpsCallableResult>() {
@Override
public void onComplete(@NonNull Task<HttpsCallableResult> task) {
if (task.isSuccessful()) {
long timestamp = (long) task.getResult().getData();
if (onComplete != null) {
onComplete.onSuccess(timestamp);
}
} else {
onComplete.onFailed();
}
}
});

}

How to get the current date and time from Firestore and save it?

First of all, using the "deviceId" as a unique identifier for your users in Firestore doesn't seem to me like a good idea. The main reason is that a user can change the device at any point in time, meaning that all the data under "users/$deviceId/" will be lost. So the best approach, in this case, is to authenticate your users with Firebase and use as a unique identifier the UID that comes from the authentication process.

To write a user object to the database, you can simply use the following lines of code:

Map<String, Object> user = new HashMap<>();
user.put("userID", deviceId);
user.put("timeStamp", FieldValue.serverTimestamp());
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(user).addOnSuccessListener(/* ... */);

Now, to read back the value of the "timeStamp" property, you need to use a "get()" call, as explained in the following lines of code:

usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Date timeStamp = document.getDate("timeStamp");
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});

Having the "timeStamp" object, now you can get the current date and time and compare them as needed in your project.

Writing the current Date and time to firebase

No, you can't directly write the server time to firebase in DateTime format.

You have one of two options:

1 - Write server time as timestamp, then when you read it when you want to use it do the conversion(that's what I do)

2 - If IT REALLY NEEDS TO BE STORED IN DateTime format, then you can write the server time stamp, read it, convert it, write it as DateTime.

How to save date and time in an orderly format Firebase & Android Studio

To get current time when someone upload the data, you can from new Date() and change your method without having a parameter argument

public static String getTimeDate() { // without parameter argument
try{
Date netDate = new Date(); // current time from here
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return sfd.format(netDate);
} catch(Exception e) {
return "date";
}
}

Firebase: Get current time without writing to the database (IOS and ANDROID)

Yes there is! It doesn't matter if it is for IOS or for Android, you can write a frunction in Cloud Functions for Firebase which will be as easy as:

exports.currentTime = functions.https.onRequest((req, res) => {
res.send({"timestamp":new Date().getTime()})
})

You can host this in Cloud Function and get the server timestamp without user interaction.

For more informations on how to set/read a timestamp in a Firebase Real-time database, please see my answer from this post.



Related Topics



Leave a reply



Submit