Updated on 2026-11-06 GMT+08:00

months_between

The months_between function is used to return the number of months between date1 and date2.

Syntax

months_between(string date1, string date2[, roundOff])

Parameters

Table 1 Parameter descriptions

Parameter

Mandatory

Type

Description

date1

Yes

DATE

or

STRING

The minuend.

Formats:
  • yyyy-mm-dd
  • yyyy-mm-dd hh:mi:ss
  • yyyy-mm-dd hh:mi:ss.ff3

date2

Yes

DATE

or

STRING

The subtrahend.

Formats:
  • yyyy-mm-dd
  • yyyy-mm-dd hh:mi:ss
  • yyyy-mm-dd hh:mi:ss.ff3

roundOff

No

BOOLEAN

Whether to round the result. The default value is false.

This parameter is currently not effective.

Return Values

Returns a value of type DOUBLE.

  • If date1 or date2 is not of type DATE or STRING, an error is returned with the message "data type mismatch".
  • If date1 or date2 is of type DATE or STRING but does not conform to the input format for date values, NULL is returned.
  • When date1 is later than date2, the return value is positive. When date2 is later than date1, the return value is negative.
  • When date1 and date2 correspond to the last day of their respective months, an integer number of months is returned. Otherwise, the calculation is the number of days from date1 minus date2 divided by 31 days, and whether the result is rounded is determined by the roundOff parameter.
  • If the date1 or date2 value is NULL, NULL is returned.

Example Code

  • Returns 0.0563172.
    select months_between('2023-08-16 10:54:00', '2023-08-14 17:00:00');
  • Returns 0.06451613.
    select months_between('2023-08-16','2023-08-14');
  • Returns NULL.
    select months_between('2023-08-16',null);
  • Returns 3.0.
    Note: May 31, 2025 and February 28, 2025 are the last days of their respective months. Therefore, the integer month 3 is returned.
    select months_between('2025-05-31','2025-02-28')
  • Returns 3.0.
    Note: The difference in days between 2025-05-28 and 2025-02-28 is 89 days.
    select months_between('2025-05-28','2025-02-28')