Compare dates ignoring milliseconds?

前端 未结 10 1275
北海茫月
北海茫月 2021-02-08 06:36

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 p

相关标签:
10条回答
  • 2021-02-08 07:23

    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 :

    DateTime dateTime = new DateTime().millisOfDay().roundFloorCopy();
    
    0 讨论(0)
  • 2021-02-08 07:25
    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();
    }
    
    0 讨论(0)
  • 2021-02-08 07:31
    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);
    }
    
    0 讨论(0)
  • 2021-02-08 07:34

    Remove milliseconds from your calendar

    cal.set(Calendar.MILLISECOND, 0);
    
    0 讨论(0)
提交回复
热议问题