You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于MomentJS计算两个日期的精确月份差值(非按天计算)

Calculate Exact Month Difference Between Two Dates (No Day-Based Calculation)

First, let's lock in the core rule from your examples: the month difference is determined solely by year and month spans, ignoring any day-of-month discrepancies (even for months with 28 or 29 days). Here's the clear breakdown of how to compute it:

Core Logic

  1. Parse the dates: Extract the year (Y), month (M), and day (D) from both date strings. Note: Your examples use two formats (YYYY/DD/MM and DD/MM/YYYY) – we'll normalize these to a consistent year/month/day structure first.
  2. Check for same month: If both dates fall in the exact same year and month (no matter the day), the difference is 0.
  3. Compute base difference: For dates in different months/years, calculate the span as:
    month_diff = (new_year - old_year) * 12 + (new_month - old_month)
    
    This works even if the new date's day is earlier than the old date's day (like in your examples 2 and 4) – we don't adjust for day differences since we're not counting days.

Let's verify this against your examples to confirm it's correct:

  • Example 0: Old=2019/01/19 (Y=2019, M=1), New=2020/03/19 (Y=2020, M=3) → (2020-2019)*12 + (3-1) = 14 ✔️
  • Example 1: Old=19/03/2020 (Y=2020, M=3), New=31/03/2020 (Y=2020, M=3) → same month → 0 ✔️
  • Example 2: Old=19/03/2020 (Y=2020, M=3), New=01/04/2020 (Y=2020, M=4) → 4-3 = 1 ✔️
  • Example 3: Old=19/03/2020, New=30/04/2020 → 4-3 =1 ✔️
  • Example 4: Old=19/03/2020, New=01/05/2020 →5-3=2 ✔️
  • Example5: Old=19/03/2020, New=01/05/2021 →(2021-2020)*12 +(5-3)=14 ✔️

Code Example (Python)

Here's a practical function that implements this logic, handling both date formats you provided:

from datetime import datetime

def calculate_month_difference(old_date_str, new_date_str):
    # Helper to parse both date formats
    def parse_date(date_str):
        parts = date_str.split('/')
        if len(parts[0]) == 4:
            # Format: YYYY/DD/MM
            return datetime(year=int(parts[0]), day=int(parts[1]), month=int(parts[2]))
        else:
            # Format: DD/MM/YYYY
            return datetime(day=int(parts[0]), month=int(parts[1]), year=int(parts[2]))
    
    old_dt = parse_date(old_date_str)
    new_dt = parse_date(new_date_str)
    
    if old_dt.year == new_dt.year and old_dt.month == new_dt.month:
        return 0
    return (new_dt.year - old_dt.year) * 12 + (new_dt.month - old_dt.month)

# Test with your examples
print(calculate_month_difference("2019/01/19", "2020/03/19"))  # Output: 14
print(calculate_month_difference("19/03/2020", "31/03/2020"))  # Output: 0
print(calculate_month_difference("19/03/2020", "01/04/2020"))  # Output: 1
print(calculate_month_difference("19/03/2020", "30/04/2020"))  # Output: 1
print(calculate_month_difference("19/03/2020", "01/05/2020"))  # Output: 2
print(calculate_month_difference("19/03/2020", "01/05/2021"))  # Output: 14

Key Notes

  • This method completely avoids day-based calculations, so it doesn't matter if a month has 28, 30, or 31 days – we only care about crossing month/year boundaries.
  • If you need to enforce a single date format, just tweak the parse_date helper to only handle your desired format.

内容的提问来源于stack exchange,提问作者rbrt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:19:09