java 时间戳 calendar,在Java中重置时间戳的时间部分

In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?

In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.

SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';

解决方案

You can go Date->Calendar->set->Date:

Date date = new Date(); // timestamp now

Calendar cal = Calendar.getInstance(); // get calendar instance

cal.setTime(date); // set cal to date

cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight

cal.set(Calendar.MINUTE, 0); // set minute in hour

cal.set(Calendar.SECOND, 0); // set second in minute

cal.set(Calendar.MILLISECOND, 0); // set millis in second

Date zeroedDate = cal.getTime(); // actually computes the new Date

I love Java dates.

Note that if you're using actual java.sql.Timestamps, they have an extra nanos field. Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object.

I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 时间戳时间之间的转换可以使用 `java.util.Date` 和 `java.time` 包的类。 1. 将时间戳转换为时间 使用 `java.util.Date` 类的构造方法可以将时间戳转换为时间。 ```java long timestamp = 1627597782000L; // 时间戳,单位毫秒 Date date = new Date(timestamp); System.out.println(date); // 输出:Fri Jul 30 10:29:42 CST 2021 ``` 2. 将时间转换为时间戳 可以使用 `java.util.Date` 类的 `getTime()` 方法获取时间时间戳值。 ```java Date date = new Date(); long timestamp = date.getTime(); System.out.println(timestamp); // 输出:1627597782000 ``` 3. 使用 java.time 包进行时间戳时间之间的转换 Java 8 引入了 `java.time` 包,提供了一组全新的日期和时间 API。可以使用 `Instant` 类将时间戳转换为时间,使用 `LocalDateTime` 类将时间转换为时间戳。 ```java long timestamp = 1627597782000L; // 时间戳,单位毫秒 Instant instant = Instant.ofEpochMilli(timestamp); System.out.println(instant); // 输出:2021-07-30T02:29:42.000Z LocalDateTime datetime = LocalDateTime.now(); long timestamp2 = datetime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); System.out.println(timestamp2); // 输出:1627597782000 ``` 上面代码,`Instant.ofEpochMilli()` 方法将时间戳转换为 `Instant` 类型的时间,`LocalDateTime.now()` 获取当前时间,`atZone()` 方法将当前时间转换为指定时区的时间,`toInstant()` 方法将指定时区的时间转换为 `Instant` 类型的时间,`toEpochMilli()` 方法获取 `Instant` 类型时间时间戳值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值