I am doing coding in android for to know the date and time of chats app when they open last time.please help.

1 Answers

0
Sandeep Malik On

i have done this in my chat app with firebase so you can try this :-

create a static method which method is used in across the app :-

public static void userStatus(String status) {
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference(onlineStatusTable).child(firebaseUser.getUid());
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("status", status);
            reference.updateChildren(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

and call this method in your activity onStart method:-

@Override
    protected void onStart() {
        userStatus(String.valueOf(System.currentTimeMillis()));
        super.onStart();
    }

and when you retrieve the milliseconds from server then converts like this :-

public static String getMyPrettyDate(long neededTimeMilis) {
        Calendar nowTime = Calendar.getInstance();
        Calendar neededTime = Calendar.getInstance();
        neededTime.setTimeInMillis(neededTimeMilis);

        if ((neededTime.get(Calendar.YEAR) == nowTime.get(Calendar.YEAR))) {

            if ((neededTime.get(Calendar.MONTH) == nowTime.get(Calendar.MONTH))) {

                if (neededTime.get(Calendar.DATE) - nowTime.get(Calendar.DATE) == 1) {
                    //here return like "Tomorrow at 12:00 AM/PM"
                    return "Tomorrow at " + DateFormat.format("hh:mm aaa", neededTime);

                } else if (nowTime.get(Calendar.DATE) == neededTime.get(Calendar.DATE)) {
                    //here return like "Today at 12:00 AM/PM"
                    return "Today at " + DateFormat.format("hh:mm aaa", neededTime);

                } else if (nowTime.get(Calendar.DATE) - neededTime.get(Calendar.DATE) == 1) {
                    //here return like "Yesterday at 12:00 AM/PM"
                    return "Yesterday at " + DateFormat.format("hh:mm aaa", neededTime);

                } else {
                    //here return like "May 31, 12:00 AM/PM"
                    return DateFormat.format("MMMM d, hh:mm aaa", neededTime).toString();
                }

            } else {
                //here return like "May 31, 12:00 AM/PM"
                return DateFormat.format("MMMM d, hh:mm aaa", neededTime).toString();
            }

        } else {
            //here return like "May 31 2010, 12:00 AM/PM" - it's a different year we need to show it
            return DateFormat.format("MMMM dd yyyy, hh:mm aaa", neededTime).toString();
        }
    }

and set you textView like this :-

status.setText(getMyPrettyDate(Long.parseLong(dataSnapshot.child("status").getValue().toString())));