Java获取当前时间的方法
常规的Java获取时间的方法
操作方法
- 01
1.通过Date类来获取时间 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String str=sdf.format(new Date()); System.out.println("当前时间是:"+str);
- 02
2.通过System类中的currentTimeMillis方法来获取当前时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String str=sdf.format(System.currentTimeMillis()); System.out.println("当前时间是:"+str);
- 03
3.通过Calendar类来获取当前时间 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH)+1; int date = c.get(Calendar.DATE); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); System.out.println(year + "-" + month + "-" + date + " " +hour + ":" +minute + ":" + second); (注意:月份从0开始所以要+1)
- 04
4. LocalDateTime类来获取当前时间 LocalDateTime dt = LocalDateTime.now(); int year = dt.getYear(); int month = dt.getMonthValue(); int date =dt.getDayOfMonth(); int hour = dt.getHour(); int minute = dt.getMinute(); int second = dt.getSecond(); System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);