How to get day, month, year and hour, minutes, second from DateTime format?

孤者浪人 提交于 2019-12-20 06:54:07

问题


I tried this following code but its a deprecated in 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();
}

Its is deprecated how to use calendar and get day, month, year?


回答1:


Set calendar time using simpleDateFormat.parse() and get field value from calendar :

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


来源:https://stackoverflow.com/questions/27035876/how-to-get-day-month-year-and-hour-minutes-second-from-datetime-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!