在Java中重置时间戳的时间部分 [英] Resetting the time part of a timestamp in Java

查看:306
本文介绍了在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中重置时间戳的时间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆