Date类是Java中用来表示日期和时间的类,它位于java.util包中。Date类提供了一些方法来获取和操作日期和时间信息。在Java 8之后,Date类已被废弃,推荐使用java.time包中的新日期时间API来代替。

下面是一些Date类的常用方法:

  1. 创建Date对象:可以使用无参构造方法创建一个表示当前时间的Date对象,也可以使用传入一个long型的参数来创建一个表示特定时间的Date对象。
Date currentDate = new Date();
Date specificDate = new Date(1612470000000L); // 2021-02-04 12:00:00
  1. 获取时间戳:可以使用getTime()方法获取Date对象表示的时间戳,即从1970年1月1日00:00:00 GMT开始计算的毫秒数。
long timestamp = currentDate.getTime();
  1. 格式化日期:Date类没有提供直接格式化日期的方法,可以借助SimpleDateFormat类来实现日期的格式化。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(currentDate);
System.out.println(formattedDate); // 2021-02-04 12:00:00
  1. 比较日期:Date类提供了before()、after()和equals()方法来比较日期的先后顺序和是否相等。
Date otherDate = new Date(1612473600000L); // 2021-02-04 12:40:00
boolean isBefore = currentDate.before(otherDate);
boolean isAfter = currentDate.after(otherDate);
boolean isEqual = currentDate.equals(otherDate);
  1. 设置日期时间:Date类提供了setTime()方法来设置日期对象的时间戳。
currentDate.setTime(1612473600000L); // 2021-02-04 12:40:00

虽然Date类已被废弃,但在一些旧的代码中可能仍然会使用到它。对于新的项目,推荐使用java.time包中的新日期时间API来操作日期和时间。