java系列之:获取当前时间和当前时间上一个小时的时间

java系列之:获取当前时间和当前时间上一个小时的时间

在这里插入图片描述

  • calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1):设置小时部分的时间,时间设置为上个小时

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestTime {

    public static void main(String[] args) {
        //getInstance()将返回一个Calendar的对象。
        Calendar calendar = Calendar.getInstance();
        //设置小时
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
        //格式化时间
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");
        //打印出时间
        System.out.println("一个小时前的时间:" + df.format(calendar.getTime()));
        System.out.println("当前的时间:" + df.format(new Date()));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
获取当前时间的上一个小时的起始时间和结束时间,可以通过以下代码实现: ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // 获取当前时间 LocalDateTime lastHourStart = now.minusHours(1).withMinute(0).withSecond(0).withNano(0); // 获取上一个小时的起始时间 LocalDateTime lastHourEnd = now.minusHours(1).withMinute(59).withSecond(59).withNano(999999999); // 获取上一个小时的结束时间 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("上一个小时的起始时间:" + formatter.format(lastHourStart)); System.out.println("上一个小时的结束时间:" + formatter.format(lastHourEnd)); } } ``` 以上代码中,我们首先通过 `LocalDateTime.now()` 方法获取当前时间,然后使用 `minusHours(1)` 方法获取上一个小时时间,接着使用 `withMinute(0)` 方法将分钟设置为0,使用 `withSecond(0)` 方法将秒数设置为0,使用 `withNano(0)` 方法将纳秒数设置为0,以获取上一个小时的起始时间。同理,使用 `withMinute(59)` 方法将分钟设置为59,使用 `withSecond(59)` 方法将秒数设置为59,使用 `withNano(999999999)` 方法将纳秒数设置为999999999,以获取上一个小时的结束时间。最后,使用 `DateTimeFormatter` 对象将时间格式化为字符串输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

快乐骑行^_^

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

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

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

打赏作者

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

抵扣说明:

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

余额充值