Java根据指定时间片段,返回时间片段内的所有小时

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

public class test {
    public static List<String> getHourListRange(String startStr , String endStr){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<String > list = new ArrayList<>();

            Calendar c = Calendar.getInstance();
            c.setTime(format.parse(startStr));

            Calendar ec = Calendar.getInstance();
            ec.setTime(format.parse(endStr));

            while (true){
                if(ec.before(c)){
                    list.add(format.format(c.getTime()));
                    break;
                }
                list.add(format.format(c.getTime()));
                c.add(Calendar.HOUR_OF_DAY,1);
            }
            return list ;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null ;
    }

    public static void main(String[] args) {
        System.out.printf(getHourListRange("2020-07-02 00:00:00", "2020-07-02 11:50:00").toString());
    }
}

输出:

[2020-07-02 00:00:00, 2020-07-02 01:00:00, 2020-07-02 02:00:00, 2020-07-02 03:00:00, 2020-07-02 04:00:00, 2020-07-02 05:00:00, 2020-07-02 06:00:00, 2020-07-02 07:00:00, 2020-07-02 08:00:00, 2020-07-02 09:00:00, 2020-07-02 10:00:00, 2020-07-02 11:00:00, 2020-07-02 12:00:00]


版权声明:本文为qq_39622065原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。