在Java中重置时间戳的时间部分

编程入门 行业动态 更新时间:2024-10-25 22:30:54
本文介绍了在Java中重置时间戳的时间部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Java中,给定时间戳记,如何将单独的时间部分重置为00:00:00,以使时间戳记表示特定日期的午夜?

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 ?

在T-SQL中,此查询将实现相同的功能,但我不知道如何在Java中执行此操作.

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';

推荐答案

您可以转到Date-> Calendar-> set-> Date:

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

我喜欢Java约会.

请注意,如果您使用的是实际的java.sql.Timestamps,则它们会有一个额外的nanos字段.当然,Calendar并不了解nano,因此会一味忽略它,并在最后创建zeroedDate时有效地将其删除,然后可以使用它来创建新的Timetamp对象.

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.

我还应该注意,Calendar不是线程安全的,所以不要以为您可以使多个线程调用一个静态的单Cal实例,以避免创建新的Calendar实例.

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.

更多推荐

在Java中重置时间戳的时间部分

本文发布于:2023-11-23 14:48:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!