首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 計算指定日期的前一天(純算法實現)

     編輯:Java 相關知識

需求

給定「yyyy-MM-dd」格式日期字符串,計算前一天日期,不依賴 Calendar 或 LocalDate,純手工邏輯演示。

核心代碼

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {
    public static String getYesterday(String today) {
        int year = Integer.parseInt(today.substring(0, 4));
        int month = Integer.parseInt(today.substring(5, 7));
        int day = Integer.parseInt(today.substring(8, 10));

        day--;
        if (day == 0) {
            month--;
            if (month == 0) {
                month = 12;
                year--;
                day = 31;
            } else {
                day = daysInMonth(year, month);
            }
        }
        return String.format("%04d-%02d-%02d", year, month, day);
    }

    private static int daysInMonth(int year, int month) {
        switch (month) {
            case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
            case 4: case 6: case 9: case 11: return 30;
            case 2:
                return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
        }
        return 31;
    }

    public static void main(String[] args) {
        System.out.println(getYesterday("2008-03-01")); // 2008-02-29
        System.out.println(getYesterday("2008-01-01")); // 2007-12-31

        // 對比 JDK API
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse("2008-03-01");
        System.out.println(sdf.format(new Date(d.getTime() - 86400000L)));
    }
}

現代 Java 推薦寫法

// Java 8+
LocalDate.parse("2008-03-01").minusDays(1).toString(); // 2008-02-29

// Java 7 Calendar
Calendar c = Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2008-03-01"));
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));

總結

手工算法適合理解日期邊界邏輯(閏年、月份天數);實際項目請直接使用 java.time.LocalDate(線程安全、不可變、API 豐富)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved