简单好用的返回明天0点,昨天0点等任意天数

简单好用的返回明天0点,昨天0点等任意天数的方法

快速入口:主要思路是在定日期格式时,直接定死时分秒

private static String timeInterval(int amount)throws Exception{
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        calendar.add(Calendar.DATE, amount);
        String strTime = sdf.format(calendar.getTime());
        return strTime;
}

 (1)当需求要求一个日期格式的时间时,可用:

 /**
     * 计算距此时往前或往后天数0点时间
     * @param amount    天数
     * @return  返回Date类型的时间
     * @throws Exception
     */
    private static Date timeInterval(int amount)throws Exception{
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        calendar.add(Calendar.DATE, amount);
        String strTime = sdf.format(calendar.getTime());
        Date time = sdf.parse(strTime);
        return time;
    }


   public static void main(String[] args) throws Exception {
        String time = timeInterval(3);
        System.out.println(time);
    }

输出结果:

输入 2 -> 2020-05-06 00:00:00

输入 5 -> 2020-05-09 00:00:00

输入 -1 -> 2020-05-03 00:00:00

 

(2)普遍适用,满足需求是返回字符串格式的时间:

 /**
     * 计算距此时往前或往后天数0点时间
     * @param amount    天数
     * @return  返回的String格式的时间
     * @throws Exception
     */
    private static String timeInterval(int amount)throws Exception{
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        calendar.add(Calendar.DATE, amount);
        String strTime = sdf.format(calendar.getTime());
        return strTime;
    }


    public static void main(String[] args) throws Exception {
        String time = timeInterval(-1);
        System.out.println(time);
    }

输出结果:

输入 2 -> 2020-05-06 00:00:00

输入 5 -> 2020-05-09 00:00:00

输入 -1 -> 2020-05-03 00:00:00

 

注:可修改参数更改日期格式new SimpleDateFormat("yyyy-MM-dd 00:00:00")

如,new SimpleDateFormat("yyyy-MM-dd"),就会输出 2020-05-06,看具体需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一碗谦谦粉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值