Home  >  Article  >  Java  >  How to compare the size of Date date type in java

How to compare the size of Date date type in java

王林
王林Original
2020-05-16 10:11:165193browse

How to compare the size of Date date type in java

The java.util.Date class implements the Comparable interface, so we can directly call the compareTo() method of Date to compare the size of the Date date type.

Syntax:

int compareTo(Date date)

Compares the Date object when this method is called with the specified date. When the two are equal, 0 is returned. If the calling object is before the specified date, a negative number is returned. The calling object returns a positive number after the specified date.

Specific code:

(Video tutorial recommendation: java video)

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
     
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     
    try {
        Date date1 = format.parse(beginTime);
        Date date2 = format.parse(endTime);
        
        int compareTo = date1.compareTo(date2);
        
        System.out.println(compareTo);
        
    } catch (ParseException e) {
        e.printStackTrace();
    }

The return value of the compareTo() method, date1 is less than date2 Returns -1, returns 1 if date1 is greater than date2, and returns 0 if they are equal.

Recommended tutorial: Getting started with java development

The above is the detailed content of How to compare the size of Date date type in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn