我正在使用下面的代码,并且能够使用 java 代码生成未来日期和过去日期等日期。如果您想添加过去的日期,只需更改方法,例如将加天数改为减天数
public String yearCalculation() {
String DATE_FORMAT = "MM/dd/yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
DateTimeFormatter dateFormat8 = DateTimeFormatter.ofPattern(DATE_FORMAT);
// Get current date
Date currentDate = new Date();
System.out.println("date : " + dateFormat.format(currentDate));
// convert date to localdatetime
LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("localDateTime : " + dateFormat8.format(localDateTime));
// plus one
localDateTime = localDateTime.plusYears(1).plusMonths(0).plusDays(0);
// convert LocalDateTime to date
Date pluseYear = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
String strDate = dateFormat.format(pluseYear);
System.out.println("\n Output of New Date : " + dateFormat.format(pluseYear));
return strDate;
}
使用下面的代码,您可以在java中生成未来和过去的数据。
public static void main(String[] args) {
//for future date
LocalDate futureDate = LocalDate.now().plusYears(1).plusMonths(5).plusDays(4);
System.out.println("Future Date : "+futureDate);
//for past dare
LocalDate pastDate = LocalDate.now().plusYears(-1).plusMonths(5).plusDays(4);
System.out.println("PastDate : "+pastDate);
}
输出:
未来日期:2025-07-10
过去日期 : 2023-07-10
永远不要使用存在严重缺陷的遗留日期时间类,这些类在几年前就被 JSR 310 中定义的现代 java.time 类所取代。我们已经使用了
Date
类中的任何一个。切勿使用 Calendar
、SimpleDateFormat
等
在尝试表示某个时刻(时间轴上的特定点)时,切勿使用
LocalDateTime
。该类讨论时区或偏移量的上下文,因此它本质上是不明确的。
要捕获 UTC 中的当前含义,请使用
Instant
。
Instant now = Instant.now() ;
要捕捉特定时区的当前时刻,请使用
ZonedDateTime
。
ZoneId zoneId = ZoneId.now( "America/Edmonton" ) ;
ZonedDateTime now = ZonedDateTime.now( zoneId ) ;