如何从DateTime格式获取日,月,年,小时,秒?

Dev*_*eva 0 datetime android date datetime-format android-calendar

我尝试了以下代码,但它在android中被弃用了

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

try {

    Date date1 = simpleDateFormat.parse("11/20/2014 8:10:00 AM");

    Log.e("date", "" + date1.getYear());

    Log.e("month", "" + date1.getmonth());

    Log.e("year", "" + date1.getYear());

    Log.e("hour", "" + date1.getHours());

    Log.e("minutes", "" + date1.getMinutes());

    Log.e("seconds", "" + date1.getSeconds());

} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

它已被弃用如何使用日历并获得日,月,年?

Har*_*ana 8

使用simpleDateFormat.parse()设置日历时间并从日历获取字段值:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
try {
     calendar.setTime(simpleDateFormat.parse("11/20/2014 8:10:00 AM"));

     Log.e("date", "" + calendar.get(Calendar.DAY_OF_MONTH));

     Log.e("month", ""+calendar.get(Calendar.MONTH));

     Log.e("year", ""+calendar.get(Calendar.YEAR));

     Log.e("hour", ""+calendar.get(Calendar.HOUR));

     Log.e("minutes", ""+calendar.get(Calendar.MINUTE));

     Log.e("seconds", ""+calendar.get(Calendar.SECOND));
} catch (ParseException e) {
   e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,在calnder月份从0到11开始,所以在月份值上加+1 (2认同)