java 比较日期忽略毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11844468/
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
Compare dates ignoring milliseconds?
提问by Jonathan
Is there a way to compare two calendar objects, but ignore milliseconds?
有没有办法比较两个日历对象,但忽略毫秒?
I have written a test case that compared two calendar objects, but there is a problem. Although all of the day, month, minutes and hours match, the milliseconds doesn't matches. I get the expected date before getting the real date:
我写了一个测试用例,比较了两个日历对象,但是有一个问题。尽管所有的天、月、分钟和小时都匹配,但毫秒不匹配。我在获得实际日期之前获得了预期日期:
/**
* @return
*/
private Calendar getExpectedOneMonthDateFromCurrentDate() {
Calendar expectedOneMonth = Calendar.getInstance();
expectedOneMonth.add(Calendar.MONTH, -1);
return expectedOneMonth;
}
assertEquals(getExpectedOneMonthDateFromCurrentDate(),
DateRange.LAST_ONE_MONTH.getToDate());
回答by mishadoff
Remove milliseconds from your calendar
从日历中删除毫秒
cal.set(Calendar.MILLISECOND, 0);
回答by Peter Lawrey
You need to use
你需要使用
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
也可能
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.
如果您只需要匹配的分钟数。
回答by Olivier Faucheux
The solution of setting the milliseconds to 0 has an issue: if the dates are 12:14:29.999 and 12:14:30.003, you will set the dates to 12:14:29 and 12:14:30 respectively and will detect a difference where you don't want to.
设置毫秒为 0 的解决方案有一个问题:如果日期是 12:14:29.999 和 12:14:30.003,则将日期分别设置为 12:14:29 和 12:14:30 并且会检测到你不想的区别。
I have thought about a Comparator:
我想过一个比较器:
private static class SecondsComparator implements Comparator<Calendar>
{
public int compare(Calendar o1, Calendar o2)
{
final long difference = o1.getTimeInMillis() - o2.getTimeInMillis();
if (difference > -1000 && difference < 1000)
return 0;
else
return difference < 0 ? 1 : -1;
}
}
public static void main(String args[])
{
Calendar c1 = Calendar.getInstance();
Utils.waitMilliseconds(100);
Calendar c2 = Calendar.getInstance();
// will return 0
System.out.println(new SecondsComparator().compare(c1,c2));
}
However, it no a good solution neither, as this Comparator breaks the following rule:
然而,这也不是一个好的解决方案,因为这个 Comparator 违反了以下规则:
The implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
实现者必须确保 x.compareTo(y)==0 意味着 sgn(x.compareTo(z)) == sgn(y.compareTo(z)),对于所有 z。
What leads to (x=y and y=z) => x=z
.
什么导致(x=y and y=z) => x=z
.
So I don't see any solution... But indeed, if you define some different dates, they aredifferent, aren't they?
所以我没有看到任何解决方案......但确实,如果你定义一些不同的日期,它们是不同的,不是吗?
回答by Manuel
IMHO the easiest way is to use truncate() from Apache Commons DateUtils (Apache Commons DateUtils) to remove the milliseconds and compare the resulting dates.
恕我直言,最简单的方法是使用 Apache Commons DateUtils ( Apache Commons DateUtils) 中的truncate()删除毫秒并比较结果日期。
回答by Dan Watt
If you are on Java 8, you can use the Java Time API, specifically Calendar::toInstant()
, followed by Instant::truncatedTo()
. Specify the granularity of truncation using ChronoUnit
enum.
如果您使用的是 Java 8,则可以使用 Java Time API,特别是Calendar::toInstant()
,后跟Instant::truncatedTo()
. 使用ChronoUnit
枚举指定截断的粒度。
myCalendar.toInstant().truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
Example.
例子。
Calendar oneMonthIsh = Calendar.getInstance();
oneMonthIsh.add(Calendar.MONTH, -1);
oneMonthIsh.add(Calendar.MINUTE, 1);
assertNotEquals(oneMonthIsh.toInstant(), getExpectedOneMonthDateFromCurrentDate());
assertEquals(oneMonthIsh.toInstant().truncatedTo(ChronoUnit.DAYS),getExpectedOneMonthDateFromCurrentDate().toInstant()
.truncatedTo(ChronoUnit.DAYS));
回答by Simon
One option is to call Calendar.set(Calendar.MILLISECOND, 0) to clear the milliseconds. Another is call getTimeInMillis() to get the time in milliseconds for both calendars. You could then divide these by 1000 before comparing to remove the milliseconds.
一种选择是调用 Calendar.set(Calendar.MILLISECOND, 0) 来清除毫秒。另一个是调用 getTimeInMillis() 以获取两个日历的时间(以毫秒为单位)。然后,您可以将这些除以 1000,然后再进行比较以删除毫秒。
回答by NewlessClubie
I'd recommend using Joda Time if you are performing anything beside the basic date manipulations. In your case you can truncate the dates like so and then compare :
如果您除了基本日期操作之外还执行任何操作,我建议您使用 Joda Time。在您的情况下,您可以像这样截断日期,然后比较:
DateTime dateTime = new DateTime().millisOfDay().roundFloorCopy();
回答by Jakub Bedná?
clearMilis(date1).compareTo(clearMilis(date2))
/**
* @param date date
*
* @return truncated miliseconds
*/
@Nonnull
public static Date clearMillis(final @Nonnull Date date)
{
DateTime result = new DateTime(date);
return result.minusMillis(result.getMillisOfSecond()).toDate();
}
回答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 );
//gc.set( Calendar.SECOND, 0 );
//block ignore millisecond
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);
}
回答by toddcscar
If you use jodaTime, the setCopy("0") method returns a DateTime object with milliseconds set to 0 to make it easy to compare:
如果使用 jodaTime,则 setCopy("0") 方法返回一个 DateTime 对象,其中毫秒设置为 0,以便于比较:
DateTime dateTimeZerodMillis = new?DateTime().millisOfSecond ().setCopy("0")