如何将 java.util.Date 实例的时间设置为 00:00:00?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20414343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:47:29  来源:igfitidea点击:

How to set time of java.util.Date instance to 00:00:00?

javadate

提问by Anthony Kong

I have a variable of the type java.util.Date.

我有一个类型的变量java.util.Date

How can I set the time part to 00:00:00?

如何将时间部分设置为 00:00:00?

I am not allowed to use an Apache Commons library or JodaTime. The java.util.Calendaris probably my only option.

我不允许使用 Apache Commons 库或 JodaTime。这java.util.Calendar可能是我唯一的选择。

采纳答案by Sionnach733

To remove time from the Dateobject completely, you could use this:

Date完全从对象中删除时间,您可以使用以下命令:

public static Date removeTime(Date date) {    
        Calendar cal = Calendar.getInstance();  
        cal.setTime(date);  
        cal.set(Calendar.HOUR_OF_DAY, 0);  
        cal.set(Calendar.MINUTE, 0);  
        cal.set(Calendar.SECOND, 0);  
        cal.set(Calendar.MILLISECOND, 0);  
        return cal.getTime(); 
    }

Pass into the method the Dateobject that you want to modify and it will return a Datethat has no hours/minutes etc.

Date将您要修改的对象传递到方法中,它将返回一个Date没有小时/分钟等的对象。

If changing the Date object itself isn't required, use SimpleDateFormat. Set the format the way you want ie. remove hours/minutes. Then call the format method and pass in the Dateobject you want changed.

如果不需要更改 Date 对象本身,请使用SimpleDateFormat. 以您想要的方式设置格式,即。删除小时/分钟。然后调用format方法,传入Date你要改变的对象。

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy");
System.out.println(sdf.format(yourDate));

回答by Basil Bourque

tl;dr

tl;博士

If you meant midnight in UTCin an old legacy java.util.Dateobject…

如果您指的是旧遗留对象中UTC 的午夜java.util.Date……

java.util.Date.from(
    OffsetDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
        LocalTime.MIN ,
        ZoneOffset.UTC
    ).toInstant()
)

If possible, discard the legacy Dateportion above and just use the modern java.time.OffsetDateTimeor java.time.Instantobject…

如果可能,丢弃Date上面的遗留部分,只使用现代java.time.OffsetDateTimejava.time.Instant对象......

OffsetDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
    LocalTime.MIN ,
    ZoneOffset.UTC
).toInstant()

If you meant midnight in a particular time zonerather than UTC…

如果您指的是特定时区的午夜而不是 UTC...

LocalDate.now()
         .atStartOfDay()

Better to specify your desired/expected time zone than rely implicitly on current default.

最好指定您想要/预期的时区,而不是隐式依赖当前默认值。

LocalDate.now( ZoneId.of( "Pacific/Auckland" )  )
         .atStartOfDay( ZoneId.of( "Pacific/Auckland" ) )

Details

细节

Caution: Not every day in every time zone has a time of 00:00:00. Daylight Savings Time can jump to 1 AM, eliminating a midnight.

注意:并非每个时区的每一天都有 00:00:00 的时间。夏令时可以跳到凌晨 1 点,消除午夜。

java.time

时间

Using java.time classes that supplant the troublesome old legacy date-time classes such as java.util.Dateand .Calendar.

使用 java.time 类取代麻烦的旧的遗留日期时间类,例如java.util.Date.Calendar

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( z );
ZonedDateTime zdt = localDate.atStartOfDay( z );

Convert to/from legacy classes

转换为/从遗留类

You should stick to the modern java.time classes whenever possible. But if you must have have instances of the old legacy classes, you can convert to/from java.time. Look to new methods added to the old classes.

您应该尽可能坚持使用现代 java.time 类。但是,如果您必须拥有旧遗留类的实例,则可以与 java.time 相互转换。寻找添加到旧类的新方法

Calendar myLegacyCal = GregorianCalendar.from( zdt ) ;

Date myLegacyDate = Date.from( zdt.toInstant() ) ;

If you want a java.util.Date, which is always in UTC time zone, to have a time-of-day of 00:00:00, use OffsetDateTimewith the constant ZoneOffset.UTC.

如果您希望java.util.Date始终处于 UTC 时区的 具有 00:00:00 的时间,请OffsetDateTime与常量 一起使用ZoneOffset.UTC

OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , ZoneOffset.UTC ) ;
Date myLegacyDate = Date.from( odt.toInstant() ) ;


About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多



Joda-Time

乔达时间

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes. This section left intact as history.

更新:Joda-Time 项目现在处于维护模式。该团队建议迁移到 java.time 类。这部分作为历史完好无损。

Use Joda-Time2.3, with a method for this very purpose: withTimeAtStartOfDay().

使用Joda-Time2.3,为此目的使用一种方法:withTimeAtStartOfDay()

// ? 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;

DateTime now = new DateTime();
DateTime firstMomentOfToday = now.withTimeAtStartOfDay();

System.out.println( "now: " + now );
System.out.println( "firstMomentOfToday: " + firstMomentOfToday );

When run…

运行时…

now: 2013-12-05T23:00:23.785-08:00
firstMomentOfToday: 2013-12-05T00:00:00.000-08:00

回答by Kayvan Tehrani

In Java 8 'java.time.LocalDate.atStartOfDay()' can be used too:

在 Java 8 中也可以使用“java.time.LocalDate.atStartOfDay()”:

    Date date = new Date();
    Instant inst = date.toInstant();
    LocalDate localDate = inst.atZone(ZoneId.systemDefault()).toLocalDate();
    Instant dayInst = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date day = Date.from(dayInst);

回答by Toi Nguyen

Like @Sionnach733, to remove time from Date, you can write this function for your DateTimeUtils with clear:

像@Sionnach733 一样,要从 Date 中删除时间,您可以使用 clear 为 DateTimeUtils 编写此函数:

public static Date getDateOnly(final Date input) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(input);
        cal.clear(Calendar.HOUR_OF_DAY);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.SECOND);
        cal.clear(Calendar.MILLISECOND);
        return cal.getTime();
    }

回答by mplungjan

Latest version courtesy of Ole.V.V

最新版本由 Ole.VV 提供

import java.time.*;

Instant dInst = LocalDate.of(1980, Month.JANUARY, 8).atStartOfDay(ZoneOffset.UTC).toInstant();
long milli = dInst.toEpochMilli();