首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaWeb 陽曆陰曆雙向同步:日期轉換核心邏輯與元件聯動

     編輯:程式設計綜合問答

核心需求

頁面兩組日期選擇器 (陽曆/陰曆),任一修改另一組自動換算顯示對應日期。

關鍵技術點

  1. 陽曆 ↔ 陰曆演算法: 採用經典「長期曆法」或「蔡勒公式」變體。Java 無內建,需自行實作或引用庫。
  2. 推薦庫: `com.github.pengfeizhou:japanese-calendar` (含農曆)、`hutool-cn` (`ChineseDate`)、或自行移植 C/C++ 開源農曆演算法 (如 `lunar.cpp`)。
  3. 前端聯動: 任一選擇器 `change` 事件 → AJAX/本地計算 → 更新另一組選擇器選項。

本地計算方案 (無需 AJAX,效能最佳)

<!-- 引入 Hutool (Maven) -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.20</version>
</dependency>

// Java 端工具類
import cn.hutool.core.date.ChineseDate;

public class CalendarUtil {
    // 陽曆 → 陰曆
    public static ChineseDate toLunar(LocalDate solar) {
        return ChineseDate.of(solar);
    }
    // 陰曆 → 陽曆
    public static LocalDate toSolar(int lunarYear, int lunarMonth, int lunarDay, boolean isLeap) {
        return ChineseDate.of(lunarYear, lunarMonth, lunarDay, isLeap).toLocalDate();
    }
}

前端 Vue/React/jQuery 同步邏輯


// jQuery 範例:假設後端提供 /api/calendar/convert?type=solar2lunar&year=2024&month=1&day=1
$('#solarYear, #solarMonth, #solarDay').change(function() {
    var y = $('#solarYear').val(), m = $('#solarMonth').val(), d = $('#solarDay').val();
    $.get('/api/calendar/convert', {type:'solar2lunar', year:y, month:m, day:d}, function(res) {
        $('#lunarYear').val(res.lunarYear);
        $('#lunarMonth').val(res.lunarMonth);
        $('#lunarDay').val(res.lunarDay);
        $('#lunarLeap').prop('checked', res.isLeap);
    });
});

// 反向同理
$('#lunarYear, #lunarMonth, #lunarDay, #lunarLeap').change(function() {
    // 組裝參數呼叫 lunar2solar API,回填陽曆三個 select
});

純前端實現 (無後端,引入 JS 版農曆庫)

  • lunar-javascript (npm/github) - 純 JS 實現陽曆/陰曆互轉、節氣、生肖。
  • 瀏覽器端直接 `new LunarDate().solarToLunar(y,m,d)` 計算,零延遲、零請求。

建議:專案為前後端分離時,優先引入 `lunar-javascript` 純前端計算,減輕後端壓力,體驗更流暢。

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