Skip to main content

Convert Gregorian calendar date to lunar calendar date in form

1. Usage scenarios

With the help of Lunar.js and YIDA JSAPI, we can convert Gregorian calendar dates to Lunar calendar. This example shows how to convert Gregorian calendar dates to Lunar calendar in YIDA.

Documentation:https://6tail.cn/calendar/api.html#lunar.festivals.html.

2. Implement functions

2.1. Form configuration

Add a solar2LunarResult variable to the data source to store the converted lunar date information.

2.2. Introduce lunar.js into didMount functions

Copy the following code to didMount.

export function didMount() {
// 引入 lunar.js
this.utils.loadScript('https://g.alicdn.com/code/lib/lunar-javascript/1.6.4/lunar.min.js').then(() => {
console.log('success');
}).catch(() => {
this.utils.toast({
title: 'JS 引入失败',
type: 'error',
});
});
}

2.3. Configure the calendar date conversion lunar information function

Copy the following code to Page JS.

/**
* 公历日期转换农历信息
* 使用文档:https://6tail.cn/calendar/api.html#lunar.new.html
* @param timeStamp:Number,公历时间戳
*/
export function solar2Lunar(timeStamp = '') {
if (!timeStamp) {
return {};
}
const solar = Solar.fromDate(new Date(timeStamp));
const lunar = solar.getLunar();
return {
yearInChinese: lunar.getYearInChinese(), // 年(中文)
monthInChinese: lunar.getMonthInChinese(), // 月(中文)
dayInChinese: lunar.getDayInChinese(), // 日(中文)
weekInChinese: lunar.getWeekInChinese(), // 星期(中文)
yearInNumber: lunar.getYear(), // 年(数字)
monthInNumber: lunar.getMonth(), // 月(数字)
dayInNumber: lunar.getDay(), // 日(数字)
weekInNumber: lunar.getWeek(), // 星期(数字)
shengXiao: lunar.getYearShengXiao(), // 生肖
};
}


2.4. Used in the date component

export function onChange({ value }) {
this.setState({
solar2LunarResult: this.solar2Lunar(value),
});
}

2.5. Bind the conversion result to the page component

3. Effect

4. Try it online

This doc is generated using machine translation. Any discrepancies or differences created in the translation are not binding and have no legal effect for compliance or enforcement purposes.
Copyright © 2024钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4