java 比较日期忽略 Joda 中 DateTime 的秒和毫秒瞬间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14947176/
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-10-31 17:58:46  来源:igfitidea点击:

Comparing dates ignoring the seconds and the milliseconds instant of DateTime in Joda

javadatetimejodatimedate-comparison

提问by Tiny

Let's assume that I have two dates like the following.

假设我有两个日期,如下所示。

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45");
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45");

I want to compare these two dates to see whether firstDateis sooner, later or equal to secondDate.

我想比较这两个日期,看看firstDate是早、晚还是等于secondDate

I could try the following.

我可以尝试以下方法。

System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isBefore(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isAfter(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.equals(secondDate));

What is produced by this code is exactly what I want.

这段代码产生的正是我想要的。

It produces the following output.

它产生以下输出。

firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = true

firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false

firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false


I need to ignore the seconds and the milliseconds portion of these dates. I have tried to use the withSecondOfMinute(0)and withMillis(0)methods like the following.

我需要忽略这些日期的秒数和毫秒部分。我曾尝试使用如下所示的withSecondOfMinute(0)withMillis(0)方法。

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillis(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillis(0);        

But it yielded the following output.

但它产生了以下输出。

firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false

firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false

firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = true

The docs of the withSecondOfMinute()method describes.

withSecondOfMinute()方法的文档描述了。

Returns a copy of this datetime with the second of minute field updated. DateTime is immutable, so there are no set methods. Instead, this method returns a new instance with the value of second of minute changed.

返回此日期时间的副本,其中更新了分钟字段的秒数。DateTime 是不可变的,因此没有设置方法。相反,此方法返回一个新实例,其中秒的值已更改。

And the docs of the method withMillis()says.

该方法的文档withMillis()说。

Returns a copy of this datetime with different millis. The returned object will be either be a new instance or this. Only the millis will change, the chronology and time zone are kept.

使用不同的毫秒返回此日期时间的副本。返回的对象将是一个新实例或 this。只有毫秒会改变,年表和时区保持不变。

Comparing dates by ignoring the time portion completely can easily be done using DateTimeComparator.getDateOnlyInstance()roughly like the following.

通过完全忽略时间部分来比较日期可以使用DateTimeComparator.getDateOnlyInstance()大致如下所示轻松完成。

if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)==0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)<0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)>0){}

How to compare two dates ignoring the specific instant in DateTime(seconds and milliseconds in this case)?

如何比较两个日期而忽略特定时刻DateTime(在这种情况下为秒和毫秒)?

采纳答案by Rohit Jain

I think you want to use DateTime#withMillisOfSecond()instead of DateTime#withMillis():

我认为你想使用DateTime#withMillisOfSecond()而不是DateTime#withMillis()

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillisOfSecond(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillisOfSecond(0);

Setting DateTime#withMillis()to 0, will reset both your dates to 1/1/1970, and hence you get truefor equalscall on them.

设置DateTime#withMillis()0,将重置您的两个日期1/1/1970,因此你trueequals他们的呼叫。

Similarly, setting DateTime#withMillisOfDay()to 0, will set the time to midnight.

同样,设置DateTime#withMillisOfDay()0,会将时间设置为midnight

回答by Steinar

Another approach is to create a DateTimeComparator with minute as lower limit:

另一种方法是创建一个以分钟为下限的 DateTimeComparator:

DateTimeComparator comparator = DateTimeComparator.getInstance(
         DateTimeFieldType.minuteOfHour());

which would ignore the second and millisecond parts of the objects being compared.

这将忽略被比较对象的第二部分和毫秒部分。

回答by Thol Voleak

public static String getFromatDateTime(Date date) {
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    final GregorianCalendar gc = new GregorianCalendar();
    gc.setTime( date );
    //gc.set( Calendar.HOUR_OF_DAY, 0 );
    //gc.set( Calendar.MINUTE, 0 );
    //block ignore second and millisecond
    gc.set( Calendar.SECOND, 0 );
    gc.set( Calendar.MILLISECOND, 0 );
    String strDate = sdfDate.format(gc.getTime());
    return strDate;
}
public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date now = new  Date();
    String currentDate = Testing.getFromatDateTime(now);
    String fullDate = "2015-12-07 14:53:39.30";
    String effDateStr = Testing.getFromatDateTime(sdfDate.parse(fullDate));

    System.out.println("Currennt Date: " + currentDate);
    System.out.println("Effective Date: " + effDateStr);
    System.out.println(currentDate.compareTo(effDateStr)==0);
}