开发过程中,很多时候我们需要获取时间,在JAVA中我们可以使用Date类来实现。

获取当前时间
Date date = new Date();
System.out.println("current time = "+date);
output=> current time = Fri Apr 01 17:24:58 CST 2022

获取当前时间的毫秒数
long time = date.getTime();
System.out.println("time = " + time);
output=> time = 1648805098557

使用SimpleDateFormat 可以格式化成我们想要的格式,例如 2022/04/16.
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String s = format.format(date);
System.out.println("format time = " + s);
output => format time = 2022/04/01

也可以解析时间格式的字符串转成Date,比如  2022-05-12 06:15:15
String time = "2022-05-12 06:15:15";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse(time);
System.out.println("date = " + date);
out => date = Thu May 12 06:15:15 GMT+08:00 2022
我们想要获取一天后的时间(当前时间+24小时),这里可以借助Calendar来实现
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE,1);
System.out.println("tomorrow = " + c.getTime());
System.out.println("tomorrow = " + format.format(c.getTime()));
output =>
  tomorrow = Sat Apr 02 17:36:47 CST 2022
  tomorrow = 2022/04/02

 也可以使用非常好用的工具hutool,附上依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.0.M3</version>
        </dependency>
// 获取当前时间
DateTime date = DateUtil.date();
System.out.println(date);
// 获取当前时间的毫秒数
System.out.println("DateUtil.current() = " + DateUtil.current());
// 获取一天后的时间
System.out.println("DateUtil.tomorrow() = " + DateUtil.tomorrow());

// or
System.out.println(DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, 1));
// 格式化时间 
System.out.println(DateUtil.format(new Date(), "yyyy/MM/dd hh:mm:ss"));
// 解析带有T的时间字符串
String taskTime = "2020-12-16T00:00:55+08:00";
System.out.println("DateUtil.parse(taskTime) = " + DateUtil.parse(taskTime));
output =>
     2022-05-13 15:45:48
        DateUtil.current() = 1652427948903
        DateUtil.tomorrow() = 2022-05-14 15:45:48
        2022/05/13 03:45:48
     DateUtil.parse(taskTime) = 2020-12-16 00:00:55