简化Java中时间范围计算的方法

发布时间:2024年01月22日

在Java中,我们经常需要计算特定时间范围的开始和结束时间,例如当天、当周、当月、当季度和当年。本文将演示如何使用Java编写一个时间范围计算器,返回包含开始和结束时间的列表。

1. 使用 java.time 包

首先,我们可以使用Java 8引入的java.time包,其中包含了现代的日期时间处理类。以下是基于这个包的实现:

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class TimeRangeCalculator {

    public static void main(String[] args) {
        List<LocalDateTime> timeRange = getTimeRange(1);
        for (LocalDateTime dateTime : timeRange) {
            System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }

        // 同样的方式可以应用于其他参数
    }

    public static List<LocalDateTime> getTimeRange(int param) {
        LocalDateTime now = LocalDateTime.now();
        List<LocalDateTime> result = new ArrayList<>();

        switch (param) {
            case 1:
                result.add(now.withHour(0).withMinute(0).withSecond(0));
                result.add(now.withHour(23).withMinute(59).withSecond(59));
                break;
            case 2:
                result.add(now.with(now.toLocalDate().with(java.time.DayOfWeek.MONDAY)).withHour(0).withMinute(0).withSecond(0));
                result.add(now.with(now.toLocalDate().with(java.time.DayOfWeek.SUNDAY)).withHour(23).withMinute(59).withSecond(59));
                break;
            case 3:
                result.add(now.with(now.toLocalDate().withDayOfMonth(1)).withHour(0).withMinute(0).withSecond(0));
                result.add(now.with(now.toLocalDate().plusMonths(1).withDayOfMonth(1)).withHour(23).withMinute(59).withSecond(59));
                break;
            case 4:
                int currentMonth = now.getMonthValue();
                int quarterStartMonth = (currentMonth - 1) / 3 * 3 + 1;
                result.add(now.with(now.toLocalDate().withMonth(quarterStartMonth).withDayOfMonth(1)).withHour(0).withMinute(0).withSecond(0));
                result.add(now.with(now.toLocalDate().withMonth(quarterStartMonth + 2).withDayOfMonth(1).plusMonths(1).minusDays(1)).withHour(23).withMinute(59).withSecond(59));
                break;
            case 5:
                result.add(now.with(now.toLocalDate().withDayOfYear(1)).withHour(0).withMinute(0).withSecond(0));
                result.add(now.with(now.toLocalDate().plusYears(1).withDayOfYear(1).minusDays(1)).withHour(23).withMinute(59).withSecond(59));
                break;
            default:
                // 处理无效参数的逻辑
                break;
        }

        return result;
    }
}

2. 使用 Calendar 类

其次,我们也可以使用传统的Calendar类。以下是基于Calendar的实现:

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

public class TimeRangeCalculator {

    public static void main(String[] args) {
        List<Calendar> timeRange = getTimeRange(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Calendar calendar : timeRange) {
            System.out.println(dateFormat.format(calendar.getTime()));
        }

        // 同样的方式可以应用于其他参数
    }

    public static List<Calendar> getTimeRange(int param) {
        Calendar now = Calendar.getInstance();
        List<Calendar> result = new ArrayList<>();

        switch (param) {
            case 1:
                result.add(getStartOfDay(now));
                result.add(getEndOfDay(now));
                break;
            case 2:
                result.add(getStartOfWeek(now));
                result.add(getEndOfWeek(now));
                break;
            case 3:
                result.add(getStartOfMonth(now));
                result.add(getEndOfMonth(now));
                break;
            case 4:
                result.add(getStartOfQuarter(now));
                result.add(getEndOfQuarter(now));
                break;
            case 5:
                result.add(getStartOfYear(now));
                result.add(getEndOfYear(now));
                break;
            default:
                // 处理无效参数的逻辑
                break;
        }

        return result;
    }

    private static Calendar getStartOfDay(Calendar calendar) {
        Calendar startOfDay = (Calendar) calendar.clone();
        startOfDay.set(Calendar.HOUR_OF_DAY, 0);
        startOfDay.set(Calendar.MINUTE, 0);
        startOfDay.set(Calendar.SECOND, 0);
        return startOfDay;
    }

    private static Calendar getEndOfDay(Calendar calendar) {
        Calendar endOfDay = (Calendar) calendar.clone();
        endOfDay.set(Calendar.HOUR_OF_DAY, 23);
        endOfDay.set(Calendar.MINUTE, 59);
        endOfDay.set(Calendar.SECOND, 59);
        return endOfDay;
    }

    private static Calendar getStartOfWeek(Calendar calendar) {
        Calendar startOfWeek = (Calendar) calendar.clone();
        startOfWeek.set(Calendar.DAY_OF_WEEK, startOfWeek.getFirstDayOfWeek());
        return getStartOfDay(startOfWeek);
    }

    private static Calendar getEndOfWeek(Calendar calendar) {
        Calendar endOfWeek = (Calendar) calendar.clone();
        endOfWeek.set(Calendar.DAY_OF_WEEK, endOfWeek.getActualMaximum(Calendar.DAY_OF_WEEK));
        return getEndOfDay(endOfWeek);
    }

    private static Calendar getStartOfMonth(Calendar calendar) {
        Calendar startOfMonth = (Calendar) calendar.clone();
        startOfMonth.set(Calendar.DAY_OF_MONTH, 1);
        return getStartOfDay(startOfMonth);
    }

    private static Calendar getEndOfMonth(Calendar calendar) {
        Calendar endOfMonth = (Calendar) calendar.clone();
        endOfMonth.set(Calendar.DAY_OF_MONTH, endOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
        return getEndOfDay(endOfMonth);
    }

    private static Calendar getStartOfQuarter(Calendar calendar) {
        Calendar startOfQuarter = (Calendar) calendar.clone();
        int currentMonth = startOfQuarter.get(Calendar.MONTH);
        int quarterStartMonth = (currentMonth / 3) * 3;
        startOfQuarter.set(Calendar.MONTH, quarterStartMonth);
        startOfQuarter.set(Calendar.DAY_OF_MONTH, 1);
        return getStartOfDay(startOfQuarter);
    }

    private static Calendar getEndOfQuarter(Calendar calendar) {
        Calendar endOfQuarter = (Calendar) calendar.clone();
        int currentMonth = endOfQuarter.get(Calendar.MONTH);
        int quarterEndMonth = ((currentMonth / 3) + 1) * 3 - 1;
        endOfQuarter.set(Calendar.MONTH, quarterEndMonth);
        endOfQuarter.set(Calendar.DAY_OF_MONTH, endOfQuarter.getActualMaximum(Calendar.DAY_OF_MONTH));
        return getEndOfDay(endOfQuarter);
    }

    private static Calendar getStartOfYear(Calendar calendar) {
        Calendar startOfYear = (Calendar) calendar.clone();
        startOfYear.set(Calendar.DAY_OF_YEAR, 1);
        return getStartOfDay(startOfYear);
    }

    private static Calendar getEndOfYear(Calendar calendar) {
        Calendar endOfYear = (Calendar) calendar.clone();
        endOfYear.set(Calendar.DAY_OF_YEAR, endOfYear.getActualMaximum(Calendar.DAY_OF_YEAR));
        return getEndOfDay(endOfYear);
    }
}

这两个实现都提供了灵活的方式,根据不同的参数返回相应时间范围的开始和结束时间。你可以根据项目需求和个人偏好选择使用java.time或Calendar。这个时间范围计算器可以轻松地扩展到其他时间单位和需求。

文章来源:https://blog.csdn.net/u010362741/article/details/135665044
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。