当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java YearMonth compareTo()用法及代码示例


Java中Yearyearth类的compareTo()方法用于比较两个YearMonth对象。它将这个YearMonth对象与作为参数传递给它的YearMonth对象进行比较。两个YearMonth实例之间的比较首先是根据Year的值进行的,然后是对Month的比较。

用法

public int compareTo(YearMonth otherYearMonth)

参数:此方法接受单个参数otherYearMonth,该参数是与此YearMonth进行比较的另一个YearMonth实例。


返回值:根据同位格返回一个整数比较器值:

  • 如果Yearyear大于otherYearMonth,则返回1。
  • 如果Yearyear小于otherYearMonth,则返回-1。
  • 如果YearMonth等于otherYearMonth,则返回0。

以下程序说明了Java中YearMonth的compareTo()方法:
示例1:

// Program to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        // Creates first YearMonth object 
        YearMonth firstYearMonth = YearMonth.of(2017, 8); 
  
        // Creates second YearMonth object 
        YearMonth secondYearMonth = YearMonth.of(2016, 11); 
  
        // compare the two YearMonth instances 
        System.out.println(firstYearMonth.compareTo(secondYearMonth)); 
    } 
}
输出:
1

示例2:

// Programt to illustrate the compareTo() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        // Creates first YearMonth object 
        YearMonth firstYearMonth = YearMonth.of(2016, 11); 
  
        // Creates second YearMonth object 
        YearMonth secondYearMonth = YearMonth.of(2016, 11); 
  
        // compare the two YearMonth instances 
        System.out.println(firstYearMonth.compareTo(secondYearMonth)); 
    } 
}
输出:
0

参考: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#compareTo-java.time.YearMonth-



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 YearMonth compareTo() method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。