Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current timestamp of firebase server in milliseconds?

I wanted to get firebase current timestamp, not able to find a way to get that. I want to save child as shown in the image. And for that I've to get timestamp and get the date accordingly. Please help...

here is the result I want to get

like image 431
Brijesh Kumar Avatar asked Jul 26 '16 14:07

Brijesh Kumar


People also ask

How do I display Firebase timestamp?

The proper way to attach a timestamp to a database update is to attach a placeholder value in your request. In the example below Firebase will replace the createdAt property with a timestamp: firebaseRef = firebase. database().

How do I get Firebase time?

To reach the timestamp of firebase server on client, you first need to write the value to the server then read the value. firebase. database(). ref('currentTime/').

What is Firebase timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

What is ServerValue timestamp?

ServerValue. TIMESTAMP in data that's written to the Firebase database. It's a placeholder for the actual time on the server and will be replaced when the server receives and writes the data.


3 Answers

You can set the server time by using ServerValue.TIMESTAMP which is a Map<String, String> type with {".sv" : "timestamp"} pair. When it's sent to the firebase database, it will be converted to a Long Unix epoch time like this 1469554720.

So the problem is, you can't set this as a key directly. The best approach is to put the timestamp inside your object and use DatabaseReference.push() to get the guaranteed unique key.

For example

DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); String key = ref.push().getKey(); // this will create a new unique key Map<String, Object> value = new HashMap<>(); value.put("name", "shesh"); value.put("address", "lucknow"); value.put("timestamp", ServerValue.TIMESTAMP); ref.child(key).setValue(value); 

If you want to save it with that format (dd-mm-yyyy), there's a hack but this is not recommended. You need to save it first (ServerValue.TIMESTAMP) to another temporary node, and then retrieve the timestamp before convert it into that format using Date class.

like image 152
Wilik Avatar answered Sep 23 '22 18:09

Wilik


Actually, you can use cloud functions, and get the timestamp via an HTTP request. The function is very simple.

exports.getTimeStamp = functions.https.onRequest((req, res)=>{
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ timestamp: Date.now() }));
});
like image 43
abdoo_salem Avatar answered Sep 23 '22 18:09

abdoo_salem


On Android I did it this way

index.js / serverside

const functions = require('firebase-functions'); 
exports.stamp = functions.https.onCall(() => {
       var d = new Date();
       console.log('TimeStamp_now : '+d.getTime());
       return { timeStamp: d.getTime() };          
   });

someclass.kt / clientside

lateinit var functions: FirebaseFunctions
var ret :Long = 0

FirebaseApp.initializeApp(this)
functions = FirebaseFunctions.getInstance()


val returnFC = functions.getHttpsCallable("stamp").call()
    returnFC.continueWith { task ->
    val resultFC = task.result?.data as Map<String, Any>
        resultFC["timeStamp"] as Long
    ret = "${resultFC["timeStamp"]}".toLong()
    val cal = Calendar.getInstance()
        cal.timeInMillis = "$ret".toLong()
    var date = DateFormat.format("dd-MM-yyyy", cal).toString()
    Log.d("current date:", date)
    Log.d("timeStamp_from_function :", "$ret")
    resultFC
}
    returnFC.addOnSuccessListener {
        Log.d("OnSuccessListener :", "success")
}    
    returnFC.addOnFailureListener {
        Log.d("OnFailureListener:", "failure")
}

I got the return and arrived at: TimestampConvert look great

like image 43
AllanRibas Avatar answered Sep 23 '22 18:09

AllanRibas