Java中提供了一些庫和方法來實現公歷與農歷的轉換。
LocalDate
和ChronoLocalDate
。可以使用LocalDate.from
方法將公歷日期轉換為農歷日期,或者使用LocalDate.now
和LocalDate.of
方法來創建農歷日期。import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
import java.time.chrono.HijrahChronology;
import java.time.chrono.HijrahDate;
// 公歷轉農歷
LocalDate date = LocalDate.of(2021, 10, 1);
Chronology hijriChronology = HijrahChronology.INSTANCE;
ChronoLocalDate hijriDate = hijriChronology.date(date);
System.out.println(hijriDate); // 輸出:Hijrah-umalqura AH 1443-02-24
// 農歷轉公歷
HijrahDate hijriDate = HijrahDate.of(1443, 2, 24);
LocalDate gregorianDate = LocalDate.from(hijriDate);
System.out.println(gregorianDate); // 輸出:2021-10-01
Calendar
類進行轉換。import org.joda.time.Chronology;
import org.joda.time.LocalDate;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.chrono.IslamicChronology;
// 公歷轉農歷
LocalDate date = new LocalDate(2021, 10, 1, ISOChronology.getInstance());
Chronology islamicChronology = IslamicChronology.getInstance();
LocalDate islamicDate = date.withChronology(islamicChronology);
System.out.println(islamicDate); // 輸出:1443-02-24
// 農歷轉公歷
LocalDate islamicDate = new LocalDate(1443, 2, 24, IslamicChronology.getInstance());
LocalDate gregorianDate = islamicDate.withChronology(ISOChronology.getInstance());
System.out.println(gregorianDate); // 輸出:2021-10-01
無論使用哪種方法,都需要注意農歷和公歷之間的轉換可能存在一些誤差或不確定性,因為不同的歷法系統和算法有不同的定義和實現。