假设我有两个日期,如下所示。比较日期,忽略Joda中DateTime的秒和毫秒瞬间
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");
我想这两个日期比较一下,看是否firstDate
迟早是,以后或等于secondDate
。
我可以试试以下内容。
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));
这段代码产生了什么正是我想要的。
它产生以下输出。
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
我需要忽略秒和这些日期的毫秒部分。我试图使用如下的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);
但它产生了以下输出。
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
withSecondOfMinute()
方法描述的文档。
返回此日期时间的副本,并更新第二分钟字段 。 DateTime是不可变的,所以没有设置方法。取而代之, 此方法返回一个新实例,其值为第 秒的值更改。
而方法withMillis()
的文档说。
返回不同毫秒的日期时间的副本。返回的 对象将成为新实例或此对象。只有毫米将 改变,年表和时区保留。
完全忽略时间部分比较日期可以很容易地使用大致如下的DateTimeComparator.getDateOnlyInstance()
来完成。
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)==0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)<0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)>0){}
如何比较两个日期忽略DateTime
特定时刻(秒和毫秒在这种情况下)?
非常感谢。完成! – Tiny 2013-02-18 23:42:29
@微小。不客气:) – 2013-02-18 23:46:08