Search code examples
androidtimereal-time

Get time from online


Is there any way to get time from online for my android app. I wanna create an android app where I need to use time which are not effected by changing device time. So I wanna get current time from online or firebase database.


Solution

  • If you don't care for millisecond accuracy, and if you are already using google firebase or don't mind using it (they provide a free tier), check this out: https://firebase.google.com/docs/database/android/offline-capabilities#clock-skew

    Basically, firebase database has a field that provides offset value between the device time and the firebase server time. You can use this offset to get the current time.

    DatabaseReference offsetRef = 
    FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
    offsetRef.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
        double offset = snapshot.getValue(Double.class);
        double estimatedServerTimeMs = System.currentTimeMillis() + offset;
      }
    
      @Override
      public void onCancelled(DatabaseError error) {
        System.err.println("Listener was cancelled");
      }
    });