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

C#实现控制台日期范围格式化输出(支持参数输入)

Solution for Condensed Date Range Formatting

Got it, let's work through this problem: we need to take an input string with two dot-separated dates, then output a condensed range where the year and month are only shown once if they match between the start and end dates. Here's a straightforward, actionable approach with code examples in popular languages.

Step 1: Break Down the Input

First, split the input string into two individual date components. Then parse each date into its day, month, and year parts using the dot separator.

Step 2: Compare and Condense

Check if both the year and month are identical for the start and end dates:

  • If they match: Combine the start day, a dash, the end day, followed by the shared month and year.
  • If they don't match: Return the full range with both complete dates separated by a dash.

Python Implementation

def format_date_range(input_str):
    # Split input into start and end date strings
    try:
        start_date_str, end_date_str = input_str.split()
    except ValueError:
        raise ValueError("Input must be two dates separated by a space (format: DD.MM.YYYY DD.MM.YYYY)")
    
    # Parse day, month, year for each date
    try:
        start_day, start_month, start_year = start_date_str.split('.')
        end_day, end_month, end_year = end_date_str.split('.')
    except ValueError:
        raise ValueError("Dates must be in DD.MM.YYYY format with dot separators")
    
    # Validate basic date components (optional but recommended)
    if not (1 <= int(start_month) <= 12) or not (1 <= int(end_month) <= 12):
        raise ValueError("Months must be between 01 and 12")
    
    # Check if year and month are identical for both dates
    if start_year == end_year and start_month == end_month:
        return f"{start_day} - {end_day}.{start_month}.{start_year}"
    else:
        # If not, return full range with both dates
        return f"{start_date_str} - {end_date_str}"

# Test the function
print(format_date_range("01.01.2017 05.01.2017"))  # Output: 01 - 05.01.2017
print(format_date_range("15.03.2023 20.03.2023"))  # Output: 15 - 20.03.2023
print(format_date_range("01.01.2017 05.02.2017"))  # Output: 01.01.2017 - 05.02.2017
print(format_date_range("30.12.2022 02.01.2023"))  # Output: 30.12.2022 - 02.01.2023

JavaScript Implementation

function formatDateRange(inputStr) {
    // Split input into start and end date strings
    const dateParts = inputStr.split(' ');
    if (dateParts.length !== 2) {
        throw new Error("Input must be two dates separated by a space (format: DD.MM.YYYY DD.MM.YYYY)");
    }
    const [startDateStr, endDateStr] = dateParts;
    
    // Parse day, month, year for each date
    const startComponents = startDateStr.split('.');
    const endComponents = endDateStr.split('.');
    if (startComponents.length !== 3 || endComponents.length !== 3) {
        throw new Error("Dates must be in DD.MM.YYYY format with dot separators");
    }
    const [startDay, startMonth, startYear] = startComponents;
    const [endDay, endMonth, endYear] = endComponents;
    
    // Validate basic date components (optional but recommended)
    if (!(parseInt(startMonth) >= 1 && parseInt(startMonth) <= 12) || !(parseInt(endMonth) >= 1 && parseInt(endMonth) <= 12)) {
        throw new Error("Months must be between 01 and 12");
    }
    
    // Check if year and month are identical for both dates
    if (startYear === endYear && startMonth === endMonth) {
        return `${startDay} - ${endDay}.${startMonth}.${startYear}`;
    } else {
        return `${startDateStr} - ${endDateStr}`;
    }
}

// Test cases
console.log(formatDateRange("01.01.2017 05.01.2017")); // "01 - 05.01.2017"
console.log(formatDateRange("01.01.2017 05.02.2017")); // "01.01.2017 - 05.02.2017"

Key Notes

  • Input Validation: The examples include basic validation to catch malformed inputs. You can expand this to check valid day ranges (e.g., 31 days for January, 28/29 for February) if needed.
  • Flexibility: If you need to handle different date formats (like MM.DD.YYYY), just adjust the order of parsed components in the code.
  • Edge Cases: The code handles cross-month and cross-year ranges correctly, falling back to the full date range when needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:44:18