java怎么获取当前日期和时间

2024-04-20

在Java中,可以使用java.util.Date类和java.util.Calendar类来获取当前日期和时间。以下是两种常用的方法:

  1. 使用Date类:

    Date currentDate = new Date();
    System.out.println("Current date and time: " + currentDate);
    
  2. 使用Calendar类:

    Calendar currentDateTime = Calendar.getInstance();
    System.out.println("Current date and time: " + currentDateTime.getTime());
    

这两种方法都会输出当前的日期和时间。需要注意的是,Date类和Calendar类在Java 8中已经被废弃,推荐使用java.time包中的类来操作日期和时间。