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
Android Fastboot Waiting for Devices
App Crashes (Sometimes) With Fatal Signal 11 (Sigsegv), Code 1
Adb Is Not Detecting My Android Device on Ubuntu
String Resource New Line /N Not Possible
Android: How to Propagate Click Event to Linearlayout Childs and Change Their Drawable
How to Change Styling of Textinput Placeholder in React Native
How to Open Particular Screen on Clicking on Push Notification for Flutter
How to Tell If a View Is Visible on Screen in Android
How to Add the Json Response into Spinner in Android Using Retrofit
How to Set Align (Right or Left) of Text in Textview, Programmatically
How to Check If a Value Exists Already in a Firebase Data Class Android
Android Studio - Failed to Apply Plugin [Id 'Com.Android.Application']
Touchableopacity Not Working Inside an Absolute Positioned View
App Restarts Rather Than Resumes
Android Refresh a Fragment List from Its Parent Activity
How to Remove Bottom Navigation View and Toolbar in Some Fragments If Using Navigation Controller