LocalDateTime类是Java 8中的日期时间类,它提供了一个minus()方法用于在当前日期时间基础上减去指定的时间量。下面是一个使用LocalDateTime.minus()函数的代码示例:
java
Copy code
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDateTime newDateTime = currentDateTime.minus(1, ChronoUnit.DAYS);
System.out.println("Current DateTime: " + currentDateTime);
System.out.println("New DateTime: " + newDateTime);
}
}
在上述示例中,我们首先通过LocalDateTime.now()方法获取当前日期时间,并将其存储在currentDateTime变量中。
然后,我们使用minus()方法在currentDateTime的基础上减去一天(24小时),并将结果存储在newDateTime变量中。这里我们使用ChronoUnit.DAYS来指定要减去的时间单位为天。
最后,通过打印输出语句,我们可以看到当前日期时间和减去一天后的新日期时间。
运行以上代码,输出结果可能如下所示(具体输出结果取决于当前时间):
yaml
Copy code
Current DateTime: 2023-10-20T15:30:45.123456789
New DateTime: 2023-10-19T15:30:45.123456789
在这个例子中,minus()函数将当前日期时间减去一天得到了新的日期时间对象,即将当前时间往前推一天。