Android 計算倆個日期差

嚶嚶嚶*發表於2020-12-23

只能算到天~ 年和月不會

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        String a = "2020-12-23 14:23:24";
        String b = "2020-12-23 10:23:24";

        long al = TimeUtils.string2Millis(a);
        long bl = TimeUtils.string2Millis(b);

        long l = al - bl;
        String timeStr = getTimeStr(l);

        System.out.println("timeStr  :" + timeStr);

    }




    public String getTimeStr(long l) {

        //總秒數
        int allSeconds = (int) (l / 1000);

        String result = null;
        if (allSeconds > 60 * 60 * 24) {// 天
            int tian = allSeconds / (60 * 60 * 24);
            int i = allSeconds % (60 * 60 * 24);

            int hour = i / (60 * 24);
            int i1 = i % (60 * 24);

            int minute = i1 / 60;
            int second = i1 % 60;
            result = "" + getNormalStr(tian) + "天" + getNormalStr(hour) + "小時" + getNormalStr(minute) + "分" + getNormalStr(second) + "秒";
        } else if (allSeconds > 60 * 60) { // 小時

            int hour = allSeconds / (60 * 60);
            int i1 = allSeconds % (60 * 60);

            int minute = i1 / 60;
            int second = i1 % 60;
            result = getNormalStr(hour) + "小時" + getNormalStr(minute) + "分" + getNormalStr(second) + "秒";
        } else if (allSeconds > 60) { // 分

            int minute = allSeconds / 60;
            int second = allSeconds % 60;
            result = getNormalStr(minute) + "分" + getNormalStr(second) + "秒";
        } else { // 秒
            result = getNormalStr(allSeconds) + "秒";
        }

        return result;
    }

    public String getNormalStr(int a) {
        if (a >= 10) {
            return a + "";
        } else {
            return "0" + a;
        }
    }

相關文章