时间格式转换和加一天操作

复制代码
    @Test
    public void testDayAdd() {
        // 小时时间段
        String start = "09:30";
        String end = "00:00";

        // 时间格式
        SimpleDateFormat sdfOne = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd ");

        Date date = new Date();

        // 当前时间格式
        String currentTimeFormat = sdfOne.format(date);

        // 时间段范围格式转换
        String startTimeFormat = sdfTwo.format(date) + start;
        String endTimeFormat = sdfTwo.format(date) + end;

        // 解析成日期格式
        Date currentDate = null;
        Date startDate = null;
        Date endDate = null;
        try {
            currentDate = sdfOne.parse(currentTimeFormat);
            startDate = sdfOne.parse(startTimeFormat);
            endDate = sdfOne.parse(endTimeFormat);
            if (end != null && end.startsWith("00")) {
                // 时间段结束以00 开头,日期时间加一天
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                // 日期加一天
                calendar.add(Calendar.DATE, 1);
                endDate = calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(currentDate);
        System.out.println(startDate);
        System.out.println(endDate);
        /**
         * 输出:
         * Wed May 04 23:28:00 CST 2022
         * Wed May 04 09:30:00 CST 2022
         * Thu May 05 00:00:00 CST 2022
         */
    }
复制代码

 

posted @   10114  阅读(370)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示