Android中根据出生年月计算生日剩余天数

计算距离下一个生日还有多少天:

 public void getBirthday() {
        String birthday = "2013-03-18";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);// 获得当前年份
        try {
            Log.i("Birthday_time", formatter.parse(birthday) + "");
            cal.setTime(formatter.parse(birthday));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int birthyear = cal.get(Calendar.YEAR);
        Log.i("Birthday_year", birthyear + "");
        while (birthyear < yearNow) {
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
            birthyear = cal.get(Calendar.YEAR);
            Log.i("Birthday_year++", birthyear + "");
        }
        Date ed = new Date();
        Log.i("Date_ed", ed + "");
        Date sd = cal.getTime();
        Log.i("Date_sd", ed + "");
        long days = 0;
        if ((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000) < 0) {//>
            days = -((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)) + 1;
            System.out.println("距离你生日还有" + days + "天");
        } else {
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
            sd = cal.getTime();
            days = -((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)) + 1;
            System.out.println("距离你生日还有" + days + "天");
        }
    }
调用上述方法即可得到距离下一个生日还需多少天。

你可能感兴趣的:(Android)