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

Java中Calendar.set方法无法修改Calendar变量问题求助

Ugh, I feel your pain with Java’s old Calendar class—it’s loaded with gotchas that can make you want to slam your laptop shut. Let’s break down the issues I spot in your snippet and fix them step by step:

Key Problems & Fixes

  1. Static Calendar Instance Risks
    If cal is a static variable, every call to calendarGet() will modify the same instance, leading to leftover state from previous runs (e.g., a year set last time bleeding into the current call). Instead, create a fresh instance each time to avoid unexpected behavior:

    Calendar cal = Calendar.getInstance(); // Fresh, clean instance every time
    
  2. Month Index Confusion
    You’re subtracting 1 from MONTH, which is correct because Calendar.MONTH is zero-indexed (January = 0, December = 11). But double-check that your MDFromDate(md) method is parsing the input month as a 1-based integer (e.g., "05" becomes 5, so 5-1 = 4 which is May). If MDFromDate already returns a zero-based value, you’ll end up with the wrong month.

  3. Missing Input Validation
    Your code grabs the input and finds the slash, but doesn’t check if the input is valid (e.g., no slash, non-numeric values, or impossible dates like 13/32). Adding validation will prevent runtime crashes:

    int slash = md.indexOf('/');
    if (slash == -1) {
        System.out.println("Invalid format! Use mm/dd.");
        return;
    }
    try {
        int inputMonth = Integer.parseInt(md.substring(0, slash));
        int inputDay = Integer.parseInt(md.substring(slash + 1));
        // Add checks: inputMonth 1-12, inputDay 1-31 (then verify against actual month max)
    } catch (NumberFormatException e) {
        System.out.println("Date must contain numbers!");
        return;
    }
    
  4. Calculating MAX_DAY Properly
    Assuming you’re trying to get the number of days in the target month, once you’ve set the calendar to the correct month and year, use this to account for leap years and varying month lengths:

    MAX_DAY = cal.getActualMaximum(Calendar.DATE);
    

Pro Tip: Ditch Calendar for Java 8+ java.time

If you’re using Java 8 or later, the java.time API is way more intuitive and avoids all the Calendar headaches. Here’s how you could rewrite this logic cleanly:

public static void calendarGet() {
    String md = getInput("What date would you like to look at?(mm/dd)");
    try {
        MonthDay monthDay = MonthDay.parse(md, DateTimeFormatter.ofPattern("MM/dd"));
        LocalDate targetDate = monthDay.atYear(Year.now().getValue());
        int targetDay = targetDate.getDayOfMonth();
        int maxDay = targetDate.lengthOfMonth();
        // Rest of your logic here
    } catch (DateTimeParseException e) {
        System.out.println("Invalid date format! Use mm/dd.");
    }
}

No zero-based months, no mutable state, and built-in validation—total game-changer.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:30:48