获取指定日期次日凌晨时间和当日凌晨时间

本文介绍如何使用Java进行日期的初始化及获取指定日期的开始时刻,并演示了如何比较两个日期的先后顺序。

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

 public static void main(String[] args) throws ParseException {

  
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //次日凌晨
        Calendar ca=Calendar.getInstance();
        Date date1 =     simpleDateFormat.parse("2021-03-26 09:04:59");
        ca.setTime(date1);
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        ca.set(Calendar.MILLISECOND, 0);
        ca.add(Calendar.DAY_OF_MONTH, 1);
        Date date3 = ca.getTime();
        String format = simpleDateFormat.format(date3);
        System.out.println(format);


        Date date2 = simpleDateFormat.parse("2021-03-25 09:04:59");

        System.out.println(date1.compareTo(date2));

    }

//返回结果

2021-03-27 00:00:00


//当日凌晨

//方法一:

        long currentTime = new Date().getTime();

        long zeroTime = currentTime - (currentTime + TimeZone.getDefault().getRawOffset()) % (1000 * 3600 * 24);

        Date zeroDate = new Date(zeroTime);
        
//方法二:

private static long getStartTimeOfDay(long now, String timeZone) {
        String tz = TextUtils.isEmpty(timeZone) ? "GMT+8" : timeZone;
        TimeZone curTimeZone = TimeZone.getTimeZone(tz);
        Calendar calendar = Calendar.getInstance(curTimeZone);
        calendar.setTimeInMillis(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值