1

I'm working on an android app where I show time and date to users for booking. Currently I'm using system time and date, but the problem is user can change it any time. So how to get correct time and date? I'm working on this problem over 3 days but I have not found any solution. Any help is appreciated.

  • 1
    maybe this will help? https://github.com/instacart/truetime-android – Zun Jul 11 '18 at 13:39
  • 1
    Take a look at this: https://stackoverflow.com/questions/13064750/how-to-get-current-time-from-internet-in-android . Is that what you need? – ParkerHalo Jul 11 '18 at 13:39
  • some years ago i used this library to do it https://github.com/dlew/joda-time-android – Joaquín Jul 11 '18 at 13:40
  • Are you planning to store your bookings in some server? If so, could you get the current time from the server too? – Ole V.V. Jul 11 '18 at 21:33

2 Answers2

0

Maybe this works:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR);
int mMinute = calendar.get(Calendar.MINUTE);
int mSecond = calendar.get(Calendar.SECOND);
System.out.print(mDay + "." + mMonth + "." + mYear + "  " + mHour + ":" + mMinute + ":" + mSecond +"\n")
user12346352
  • 176
  • 2
  • 20
0

This worked fine for me, but it is inaccurate in seconds, that's not a big problem for me. Used firebase realtime database.

final DatabaseReference offsetRef = 
FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
    offsetRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            long offset = snapshot.getValue(Long.class);
            long estimatedServerTimeMs = System.currentTimeMillis() + offset;
            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
            Date resultdate = new Date(estimatedServerTimeMs);
            Log.d(Tag,"date from firebase is "+sdf.format(resultdate).toString());
        }

        @Override
        public void onCancelled(DatabaseError error) {
            System.err.println("Listener was cancelled");
            Log.d(Tag,"error is "+error.toString());
        }
    });