Android-Get DOB来自几年,几个月和几天

时间:2015-10-18 05:23:55

标签: android

我想显示指定年份,月份和日期的 DOB

,但无法计算月和日。请帮帮我。

1 个答案:

答案 0 :(得分:0)

如果要将特定日期设置为日期选择器,请使用以下代码更新日期选择器中的日期。

Calendar cal = Calendar.getInstance();
    cal.set(2013, 05, 23);
    cal.add(Calendar.MONTH, 1);

    int xxday = cal.get(Calendar.DATE);
    int xxmonth = cal.get(Calendar.MONTH);
    int xxyear = cal.get(Calendar.YEAR);

    datepicker.init(xxyear, xxmonth, xxday, null);

如果您想从DatePicker获取日期,请尝试此操作

DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
 int day = datePicker.getDayOfMonth();
 int month = datePicker.getMonth() + 1;
 int year = datePicker.getYear();

两个日期之间的差异:

String toyBornTime = "2014-06-18 12:56:50";
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    try {

        Date oldDate = dateFormat.parse(toyBornTime);
        System.out.println(oldDate);

        Date currentDate = new Date();

        long diff = currentDate.getTime() - oldDate.getTime();
        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (oldDate.before(currentDate)) {

            Log.e("oldDate", "is previous date");
            Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
                    + " hours: " + hours + " days: " + days);

        }

        // Log.e("toyBornTime", "" + toyBornTime);

    } catch (ParseException e) {

        e.printStackTrace();
    }

如果您想要月份和年份。

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);