主要有以下方式,代码如下:
1.使用Calendar
Calendar now = Calendar.getInstance(); System.out.println("年:" + now.get(Calendar.YEAR)); System.out.println("月:" + (now.get(Calendar.MONTH) + 1)); System.out.println("日:" + now.get(Calendar.DAY_OF_MONTH)); System.out.println("时:" + now.get(Calendar.HOUR_OF_DAY)); System.out.println("分:" + now.get(Calendar.MINUTE)); System.out.println("秒:" + now.get(Calendar.SECOND));
2.使用Date
Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("当前时间:" + sdf.format(d));
3.使用jdk8新的时间api,LocalDateTime、LocalDate、LocalTime
① jdk8 日期与时间:LocalDateTime
LocalDateTime nowDateTime = LocalDateTime.now(); System.out.println(nowDateTime); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println(dateTimeFormatter.format(nowDateTime)); // 反着使用也可以 System.out.println(nowDateTime.format(dateTimeFormatter));
②jdk8 日期: LocalDate
LocalDate nowDate = LocalDate.now(); System.out.println(nowDate); DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); System.out.println(dateFormatter.format(nowDate)); // 反着使用也可以 System.out.println(nowDate.format(dateFormatter));
③jdk8 时间:LocalTime
LocalTime nowTime = LocalTime.now(); System.out.println(nowTime); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); System.out.println(timeFormatter.format(nowTime)); // 反着使用也可以 System.out.println(nowTime.format(timeFormatter));