Java实现查询近一周、一个月、半年等工具类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 近一周、近一个月、近三个月、近半年、近一年时间段内日期显示
 *
 * @author ygq
 * @date 2023年12月5日
 **/
public class DateIntervalUtils {

    /**
     * 最近一周的所有日期
     * 
     * @return
     */
    public static List<String> getNearlyWeekDates() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去七天
        c.setTime(new Date());
        String today = format.format(new Date());
        c.add(Calendar.DATE, -7);
        Date d = c.getTime();
        String day = format.format(d);
        List<String> result = getBetweenDates(day, today, false);
        return result;
    }

    /**
     * 最近一个月的所有日期
     * 
     * @return
     */
    public static List<String> getNearlyMonthDates() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去一月
        c.setTime(new Date());
        String today = format.format(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = format.format(m);
        List<String> result = getBetweenDates(mon, today, false);

        return result;
    }

    /**
     * 最近三个月的所有日期
     *
     * @return
     */
    public static List<String> getNearlyThMonthDates() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去一月
        c.setTime(new Date());
        String today = format.format(new Date());
        c.add(Calendar.MONTH, -3);
        Date m = c.getTime();
        String mon = format.format(m);
        List<String> result = getBetweenDates(mon, today, false);

        return result;
    }

    /**
     * 最近半年的所有日期
     *
     * @return
     */
    public static List<String> getNearlySixMonthDates() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去一月
        c.setTime(new Date());
        String today = format.format(new Date());
        c.add(Calendar.MONTH, -6);
        Date m = c.getTime();
        String mon = format.format(m);
        List<String> result = getBetweenDates(mon, today, false);

        return result;
    }

    /**
     * 最近一年的所有月份
     * 
     * @return
     */
    public static List<String> getNearlyYearDates() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去一年
        c.setTime(new Date());
        String today = format.format(new Date());
        c.add(Calendar.MONTH, -12);
        Date y = c.getTime();
        String year = format.format(y);
        // 如果要获取近一年内的所有月份
        // List<String> result = getMonthsBetweenDates(year, today);
        // 如果要获取近一年内的所有日期
        List<String> result = getBetweenDates(year, today, false);
        return result;
    }

    /**
     * 补全给定时间内的所有周,包含最开始的
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getWeeksBetweenDates(String startTime, String endTime) {
        List<String> result = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date start = null;
        Date end = null;
        try {
            start = format.parse(startTime);
            end = format.parse(endTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(start);
            result.add(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.WEEK_OF_YEAR));
            while (calendar.getTime().before(end)) {
                calendar.add(Calendar.WEEK_OF_YEAR, 1);
                String weekStr = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.WEEK_OF_YEAR);
                result.add(weekStr);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 补全给定起止时间区间内的所有日期
     *
     * @param startTime
     * @param endTime
     * @param isIncludeStartTime
     * @return
     */
    public static List<String> getBetweenDates(String startTime, String endTime, boolean isIncludeStartTime) {
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            // 定义起始日期
            Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
            // 定义结束日期 可以去当前月也可以手动写日期。
            Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
            // 定义日期实例
            Calendar dd = Calendar.getInstance();
            // 设置日期起始时间
            dd.setTime(d1);
            if (isIncludeStartTime) {
                result.add(format.format(d1));
            }
            // 判断是否到结束日期
            while (dd.getTime().before(d2)) {
                // 进行当前日期加1
                dd.add(Calendar.DATE, 1);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String str = sdf.format(dd.getTime());
                result.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 补全给定时间区内的所有月份
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getMonthsBetweenDates(String startTime, String endTime) {
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            // 定义起始日期
            Date d1 = new SimpleDateFormat("yyyy-MM").parse(startTime);
            // 定义结束日期 可以去当前月也可以手动写日期。
            Date d2 = new SimpleDateFormat("yyyy-MM").parse(endTime);
            // 定义日期实例
            Calendar dd = Calendar.getInstance();
            // 设置日期起始时间
            dd.setTime(d1);
            result.add(format.format(d1));
            // 判断是否到结束日期
            while (dd.getTime().before(d2)) {
                // 进行当前日期月份加1
                dd.add(Calendar.MONTH, 1);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                String str = sdf.format(dd.getTime());
                result.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

### 实现指定时间段的时间范围 为了实现在前端获取默认今天为结束日的7天、30天、最一个完整的星期和最一个完整月份的时间段,可以利用 JavaScript 的 `Date` 对象来计算这些日期区间。 #### 七天时间范围 通过创建一个新的 `Date` 对象并减去相应的毫秒数来获得过去几天的具体日期: ```javascript function getPastDaysRange(days) { const today = new Date(); const pastDate = new Date(today); pastDate.setDate(today.getDate() - days); return { start: formatDate(pastDate), end: formatDate(today) }; } function formatDate(date) { let day = date.getDate().toString().padStart(2, '0'); let month = (date.getMonth() + 1).toString().padStart(2, '0'); // Months are zero-based let year = date.getFullYear(); return `${year}-${month}-${day}`; } ``` 对于七天的情况,则调用此函数传入参数7即可得到所需的结果[^1]。 #### 三十天时间范围 同样的逻辑适用于三十天的情形,只需调整传递给上述辅助函数的参数值为30即可完成相应功能。 #### 最的一个完整星期 要取得最的一整个星期内的所有日子,可以从当前日期出发向前追溯到上一个星期的第一天(即上周日),再往前推算至该周的第一个工作日(周一)。这里假设每周从周一开始计算: ```javascript function getLastFullWeekRange() { const today = new Date(); const currentDayOfWeek = today.getDay(); // Sunday is 0, Monday is 1... const lastSunday = new Date(today); lastSunday.setDate(today.getDate() - ((currentDayOfWeek === 0 ? 7 : currentDayOfWeek))); const previousMonday = new Date(lastSunday); previousMonday.setDate(lastSunday.getDate() - 6); // Go back to the beginning of that week. return { start: formatDate(previousMonday), end: formatDate(lastSunday) }; } ``` 这段代码会返回最一次完整的那一整周内的起始与终止日期字符串表示形式。 #### 最的一个完整月份 最后,针对最靠现在的那个月份内所有有效日期的选择,可以通过设置月初和月末两个极端情况下的日期来进行处理: ```javascript function getLastFullMonthRange() { const now = new Date(); const thisYear = now.getFullYear(); const thisMonth = now.getMonth(); const firstDayOfMonth = new Date(thisYear, thisMonth, 1); const lastDayOfPrevMonth = new Date(firstDayOfMonth); lastDayOfPrevMonth.setMonth(now.getMonth(), 0); // Set to the last day of the previous month return { start: formatDate(new Date(thisYear, thisMonth - 1, 1)), end: formatDate(lastDayOfPrevMonth) }; } ``` 以上就是基于纯JavaScript实现的不同类型固定周期内日期选取的方法介绍。如果项目中已经集成了某些UI库比如Layui或其他第三方组件,也可以考虑查阅其官方文档寻找是否有内置的支持选项或是插件可以直接满足需求而不必手动编写额外的功能模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

再写一行代码就下班

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值