Compare dates ignoring milliseconds?

前端 未结 10 1540
北海茫月
北海茫月 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: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);
    }
    

提交回复
热议问题