gpt4 book ai didi

java - 如何从 Date 对象中修剪分钟、小时和秒?

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:32 25 4
gpt4 key购买 nike

我需要制作以日期为键的 map 。如果 2 个日期对象具有相同的 getTime() 方法值,则它们是相等的。

我只对年月日感兴趣。我如何修剪不必要的小时和分钟以获得“明确”的日期?

最佳答案

您可以创建一个 trim 方法:

public static Date trim(Date date) {
Calendar cal = Calendar.getInstance();
cal.clear(); // as per BalusC comment.
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();
}

像这样使用它:

 map.put( trim( aDate ), xyz() );

...

 map.get( trim( otherDate ));

这是一个完整的工作示例:

import java.util.Calendar;
import java.util.Date;
import static java.util.Calendar.*;
import static java.lang.System.out;


public class DateTest {
public static void main( String [] args ) throws InterruptedException {
Date date = new Date();
Thread.sleep(1);
Date other = new Date();
out.printf("equals? = %s, hashCode? = %s %n", (date.equals(other)), (date.hashCode() == other.hashCode()));

Date todayeOne = trim( date );
Date todayTwo = trim( date );


out.printf("equals? = %s, hashCode? = %s %n", (todayeOne.equals(todayTwo)), (todayeOne.hashCode() == todayTwo.hashCode()));

}

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

}

输出:

$ java DateTest 
equals? = false, hashCode? = false
equals? = true, hashCode? = true

关于java - 如何从 Date 对象中修剪分钟、小时和秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2775411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com