java 时间分割器

这是一个Java程序,用于将两个日期之间的时间间隔按分钟拆分为一系列日期。它首先检查开始日期是否早于结束日期,然后计算间隔分钟数,并创建一个包含这些间隔的日期列表。示例展示了从指定日期开始向前回溯一个月的日期序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jd.vehicle.worker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: syyjy
 * Date: 13-6-26
 * Time: 下午3:00
 * To change this template use File | Settings | File Templates.
 */
public class DateSplit {

    private static List<Date> dateSplit(Date startDate, Date endDate) throws Exception {
        if (!startDate.before(endDate)) throw new Exception("开始时间应该在结束时间之后");
        Long spi = endDate.getTime() - startDate.getTime();
        Long step = spi / 60;

        List<Date> dateList = new ArrayList<Date>();
        dateList.add(endDate);
        for (int i = 1; i <= 60; i++) {
            dateList.add(new Date(endDate.getTime() - step * i));
        }
        return dateList;
    }

    private static Date getLastMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);    //得到前一天
        cal.add(Calendar.MONTH, -1);    //得到前一个月
        long date = cal.getTimeInMillis();
        System.out.println(format.format(new Date(date)) );
        return new Date(date);
    }


    public static void main(String[] args) throws ParseException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = sdf.parse("2012-10-01 00:00:00");
            Date end = sdf.parse("2012-09-01 00:00:00");
            List<Date> lists = dateSplit(getLastMonth(),new Date());
            if (!lists.isEmpty()) {
                for (Date date : lists) {
                    System.out.println(sdf.format(date));
                }

            }
        } catch (Exception e) {
            System.out.print(e);
        }


    }
}


2012-09-01 00:00:00
2012-09-02 00:00:00
2012-09-03 00:00:00
2012-09-04 00:00:00
2012-09-05 00:00:00
2012-09-06 00:00:00
2012-09-07 00:00:00
2012-09-08 00:00:00
2012-09-09 00:00:00
2012-09-10 00:00:00
2012-09-11 00:00:00
2012-09-12 00:00:00
2012-09-13 00:00:00
2012-09-14 00:00:00
2012-09-15 00:00:00
2012-09-16 00:00:00
2012-09-17 00:00:00
2012-09-18 00:00:00
2012-09-19 00:00:00
2012-09-20 00:00:00
2012-09-21 00:00:00
2012-09-22 00:00:00
2012-09-23 00:00:00
2012-09-24 00:00:00
2012-09-25 00:00:00
2012-09-26 00:00:00
2012-09-27 00:00:00
2012-09-28 00:00:00
2012-09-29 00:00:00
2012-09-30 00:00:00
2012-10-01 00:00:00

Process finished with exit code 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值