1、使用 Java 中的 LocalDate
类
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 创建日期格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 输出最近 30 天的日期
for (int i = 0; i < 30; i++) {
System.out.println(currentDate.minusDays(i).format(formatter));
}
}
}
这个程序首先获取当前日期,然后使用循环逐个减去天数,以获取最近 30 天的日期,并使用指定的格式进行格式化输出。
2、使用系统时间
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// 获取当前系统时间
Calendar calendar = Calendar.getInstance();
// 创建日期格式化器
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 输出最近 30 天的日期
for (int i = 0; i < 30; i++) {
System.out.println(sdf.format(calendar.getTime()));
// 减去一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
}
}
这个程序首先获取当前系统时间的Calendar
对象,然后使用SimpleDateFormat
来格式化日期。接下来,通过循环逐个减去天数,并输出最近 30 天的日期。
3、使用 new Date()
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 获取当前系统时间
Date currentDate = new Date();
// 创建日期格式化器
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 输出最近 30 天的日期
for (int i = 0; i < 30; i++) {
System.out.println(sdf.format(currentDate));
// 减去一天
long timeInMillis = currentDate.getTime();
timeInMillis -= 24 * 60 * 60 * 1000; // 减去一天的毫秒数
currentDate.setTime(timeInMillis);
}
}
}
这个程序也是通过循环逐个减去天数,并输出最近 30 天的日期。