这样的类似的需求,不要自己去写,应该使用工具类来完成,自己写可能考虑的不全面,有些错误。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse("2019-01-10 09:24:07"); Calendar cal = Calendar.getInstance(); cal.setTime(date); System.out.println("年: " + cal.get(Calendar.YEAR)); System.out.println("月: " + (cal.get(Calendar.MONTH) + 1) + ""); System.out.println("日: " + cal.get(Calendar.DAY_OF_MONTH)); System.out.println("时: " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("分: " + cal.get(Calendar.MINUTE)); System.out.println("秒: " + cal.get(Calendar.SECOND));