java日期工具类DateUtil-续二(二)
private final static String[] lunarString2 = { "初", "十", "廿", "卅", "正", "腊", "冬", "闰" };
/** 农历年 */
private int lunarYear;
/** 农历月 */
private int lunarMonth;
/** 农历日 */
private int lunarDay;
/** 是否是闰月 */
private boolean isLeap;
/** 是否是闰年 */
private boolean isLeapYear;
/** 某农历月的最大天数 */
private int maxDayInMonth = 29;
/**
* 通过 TimeInMillis 构建农历信息
* @param TimeInMillis
*/
public SimpleLunarCalendar(long TimeInMillis) {
this.init(TimeInMillis);
}
/**
* 通过 Date 对象构建农历信息
* @param date 指定日期对象
*/
public SimpleLunarCalendar(Date date) {
if (date == null)
date = new Date();
this.init(date.getTime());
}
/**
* 农历初始化
* @param timeInMillis 时间毫秒数
*/
private void init(long timeInMillis) {
if (timeInMillis > minTimeInMillis && timeInMillis < maxTimeInMillis) {
// 以农历为1900年正月一日的1900-1-31作为起始日期
Calendar baseDate = new GregorianCalendar(1900, 0, 31);
// 距离起始日期间隔的总天数
long offset = (timeInMillis - baseDate.getTimeInMillis()) / 86400000;
// 默认农历年为1900年,且由此开始推算农历年份
this.lunarYear = 1900;
int daysInLunarYear = SimpleLunarCalendar.getLunarYearDays(this.lunarYear);
// 递减每个农历年的总天数,确定农历年份
while (this.lunarYear < 2100 && offset >= daysInLunarYear) {
offset -= daysInLunarYear;
daysInLunarYear = SimpleLunarCalendar.getLunarYearDays(++this.lunarYear);
}
// 获取该农历年的闰月月份
int leapMonth = SimpleLunarCalendar.getLunarLeapMonth(this.lunarYear);
// 没有闰月则不是闰年
this.isLeapYear = leapMonth > 0;
// 默认农历月为正月,且由此开始推荐农历月
int lunarMonth = 1;
// 是否递减农历月
boolean isDecrease = true;
boolean isLeap = false;
int daysInLunarMonth = 0;
// 递减每个农历月的总天数,确定农历月份
while (lunarMonth < 13 && offset > 0) {
if (isLeap && !isDecrease) {
// 该农历年闰月的总天数
daysInLunarMonth = SimpleLunarCalendar.getLunarLeapDays(this.lunarYear);
isDecrease = true;
} else {
// 该农历年正常农历月份的天数
daysInLunarMonth = SimpleLunarCalendar.getLunarMonthDays(this.lunarYear, lunarMonth);
}
if (offset < daysInLunarMonth) {
break;
}
offset -= daysInLunarMonth;
// 如果农历月是闰月,则不递增农历月份
if (leapMonth == lunarMonth && isLeap == false) {
isDecrease = false;
isLeap = true;
} else {
lunarMonth++;
}
}
// 如果daysInLunarMonth为0则说明默认农历月即为返回的农历月
this.maxDayInMonth = daysInLunarMonth != 0 daysInLunarMonth : SimpleLunarCalendar.getLunarMonthDays(this.lunarYear, lunarMonth);
this.lunarMonth = lunarMonth;
this.isLeap = (lunarMonth == leapMonth && isLeap);
this.lunarDay = (int) offset + 1;
}
}
/**
* 获取某农历年的总天数
* @param lunarYear 农历年份
* @return 该农历年的总天数
*/
private static int getLunarYearDays(int lunarYear) {
// 按小月计算,农历年最少有12 * 29 = 348天
int daysInLunarYear = 348;
// 遍历前12位