頁面兩組日期選擇器 (陽曆/陰曆),任一修改另一組自動換算顯示對應日期。
<!-- 引入 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();
}
}
// 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
});
lunar-javascript (npm/github) - 純 JS 實現陽曆/陰曆互轉、節氣、生肖。建議:專案為前後端分離時,優先引入 `lunar-javascript` 純前端計算,減輕後端壓力,體驗更流暢。