Java中提供了一些庫(kù)和方法來(lái)實(shí)現(xiàn)公歷與農(nóng)歷的轉(zhuǎn)換。
LocalDate
和ChronoLocalDate
??梢允褂?code>LocalDate.from方法將公歷日期轉(zhuǎn)換為農(nóng)歷日期,或者使用LocalDate.now
和LocalDate.of
方法來(lái)創(chuàng)建農(nóng)歷日期。import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
import java.time.chrono.HijrahChronology;
import java.time.chrono.HijrahDate;
// 公歷轉(zhuǎn)農(nóng)歷
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
// 農(nóng)歷轉(zhuǎn)公歷
HijrahDate hijriDate = HijrahDate.of(1443, 2, 24);
LocalDate gregorianDate = LocalDate.from(hijriDate);
System.out.println(gregorianDate); // 輸出:2021-10-01
Calendar
類進(jìn)行轉(zhuǎn)換。import org.joda.time.Chronology;
import org.joda.time.LocalDate;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.chrono.IslamicChronology;
// 公歷轉(zhuǎn)農(nóng)歷
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
// 農(nóng)歷轉(zhuǎn)公歷
LocalDate islamicDate = new LocalDate(1443, 2, 24, IslamicChronology.getInstance());
LocalDate gregorianDate = islamicDate.withChronology(ISOChronology.getInstance());
System.out.println(gregorianDate); // 輸出:2021-10-01
無(wú)論使用哪種方法,都需要注意農(nóng)歷和公歷之間的轉(zhuǎn)換可能存在一些誤差或不確定性,因?yàn)椴煌臍v法系統(tǒng)和算法有不同的定義和實(shí)現(xiàn)。