首页 > 解决方案 > 我想通过android中的编程知道任何聊天应用程序的打开日期和时间

问题描述

我正在android中进行编码,以了解聊天应用程序上次打开时的日期和时间。请帮助。

标签: android

解决方案


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())));

推荐阅读