Method: Date#<=>

Defined in:
ext/date/date_core.c

#<=>(other) ⇒ -1, ...

Compares self and other, returning:

  • -1 if other is larger.

  • 0 if the two are equal.

  • 1 if other is smaller.

  • nil if the two are incomparable.

Argument other may be:

  • Another Date object:

    d = Date.new(2022, 7, 27) # => #<Date: 2022-07-27 ((2459788j,0s,0n),+0s,2299161j)>
    prev_date = d.prev_day    # => #<Date: 2022-07-26 ((2459787j,0s,0n),+0s,2299161j)>
    next_date = d.next_day    # => #<Date: 2022-07-28 ((2459789j,0s,0n),+0s,2299161j)>
    d <=> next_date           # => -1
    d <=> d                   # => 0
    d <=> prev_date           # => 1
    
  • A DateTime object:

    d <=> DateTime.new(2022, 7, 26) # => 1
    d <=> DateTime.new(2022, 7, 27) # => 0
    d <=> DateTime.new(2022, 7, 28) # => -1
    
  • A numeric (compares self.ajd to other):

    d <=> 2459788 # => -1
    d <=> 2459787 # => 1
    d <=> 2459786 # => 1
    d <=> d.ajd   # => 0
    
  • Any other object:

    d <=> Object.new # => nil
    

Returns:

  • (-1, 0, 1, nil)


6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
# File 'ext/date/date_core.c', line 6825

static VALUE
d_lite_cmp(VALUE self, VALUE other)
{
    if (!k_date_p(other))
	return cmp_gen(self, other);

    {
	get_d2(self, other);

	if (!(simple_dat_p(adat) && simple_dat_p(bdat) &&
	      m_gregorian_p(adat) == m_gregorian_p(bdat)))
	    return cmp_dd(self, other);

	{
	    VALUE a_nth, b_nth;
	    int a_jd, b_jd;

	    m_canonicalize_jd(self, adat);
	    m_canonicalize_jd(other, bdat);
	    a_nth = m_nth(adat);
	    b_nth = m_nth(bdat);
	    if (f_eqeq_p(a_nth, b_nth)) {
		a_jd = m_jd(adat);
		b_jd = m_jd(bdat);
		if (a_jd == b_jd) {
		    return INT2FIX(0);
		}
		else if (a_jd < b_jd) {
		    return INT2FIX(-1);
		}
		else {
		    return INT2FIX(1);
		}
	    }
	    else if (f_lt_p(a_nth, b_nth)) {
		return INT2FIX(-1);
	    }
	    else {
		return INT2FIX(1);
	    }
	}
    }
}