java 已知当前时间 如何快速的得出近30天每天的时间

46 篇文章 0 订阅

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 天的日期。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ptw-cwl

谢谢老板的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值