获取当前系统时间:
//获取当前系统时间
Date date =new Date();
log.info("当前系统时间,没有经过格式化:"+date);
//当前系统时间,没有经过格式化:Wed Feb 22 22:14:54 CST 2023
//创建一个项目中常用的时间格式化类:SimpleDateFormat(),构造参数是String类型的时间形式,"yyyy-MM-dd HH:mm:ss"
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info("经过时间格式化的日期时间:"+sdf.format(date));
//经过时间格式化的日期时间:2023-02-22 22:20:03
获取当前系统时间的前一天时间:
//获取当前系统时间的前一天日期时间
//创建时间格式化类,定义好要格式化的时间类型
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
//创建日历类
Calendar calendar = Calendar.getInstance();
//设置日历时间当前时间
calendar.setTime(date);
//日历时间-1
calendar.add(Calendar.DAY_OF_MONTH, -1);
//获取-1 之后的时间
date = calendar.getTime();
log.info("当前系统时间:"+df.format(new Date()));
//当前系统时间:2023-02-22 22:31:23
log.info("当前系统时间的前一天时间:"+df.format(date));
//当前系统时间的前一天时间:2023-02-21 22:31:23
当前系统时间的后一天时间:
//获取当前系统时间的后一天日期时间
//创建时间格式化类,定义好要格式化的时间类型
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
//创建日历类
Calendar calendar = Calendar.getInstance();
//设置日历时间
calendar.setTime(date);
//日历时间+1
calendar.add(Calendar.DAY_OF_MONTH, +1);
//获取+1之后的时间
date = calendar.getTime();
log.info("当前系统时间:"+df.format(new Date()));//当前系统时间:2023-02-22 22:31:23
log.info("当前系统时间的后一天时间:"+df.format(date));//当前系统时间的后一天时间:2023-02-23 22:35:33
获取当前系统的毫秒时间:
//获取当前系统的毫秒数
log.info("获取当前系统的毫秒数:"+System.currentTimeMillis());
//获取当前系统的毫秒数:1677076818916
工作中用的比较多的时间格式化方法:
//工作中用的比较多的时间格式化的类
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//构造方法传String类型的指定时间格式化参数
//然后通过SimpleDateFormat的format(),传进去要格式化的时间
System.out.println(sdf.format(new Date()));
时间格式化的(yyyyMMss )的解析搜索参考网友的解析:
SimpleDateFormat格式化日期的方法和参数_攻城狮Kevin的博客-CSDN博客_simpledateformat