使用 LocalDateTime
类来获取当前时间,并使用其提供的方法来计算昨天的时间。
以下是获取昨天同一时间的几种方法:
方法 1: 使用 minusDays
方法
import java.time.LocalDateTime;
public class DateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(); // 获取当前的日期和时间
LocalDateTime yesterday = now.minusDays(1); // 获取昨天的日期和时间
System.out.println("现在的时间是: " + now);
System.out.println("昨天的时间是: " + yesterday);
}
}
方法 2: 使用 Duration
类
import java.time.Duration;
import java.time.LocalDateTime;
public class DateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(); // 获取当前的日期和时间
LocalDateTime yesterday = now.minus(Duration.ofDays(1)); // 使用 Duration 减去一天
System.out.println("现在的时间是: " + now);
System.out.println("昨天的时间是: " + yesterday);
}
}
方法 3: 使用 Period
类
import java.time.LocalDateTime;
import java.time.Period;
public class DateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(); // 获取当前的日期和时间
LocalDateTime yesterday = now.minus(Period.ofDays(1));// 使用 Period 减去一天
System.out.println("现在的时间是: " + now);
System.out.println("昨天的时间是: " + yesterday);
}
}
这三个方法都将输出当前时间以及昨天同一时间。通常情况下,minusDays
方法是计算之前或之后日期的最直接和最常用的方法。
需要注意的是,这些操作返回的都是新的 LocalDateTime
实例,因为 LocalDateTime
是不可变类型。原始的 LocalDateTime
实例不会被修改。