跳到主要内容

表单中公历日期转农历日期

1. 使用场景

借助 Lunar.js 和宜搭 JSAPI 我们可以实现公历日期转农历,本例学习一下在宜搭中如何实现公历日期转农历。

使用文档 : https://6tail.cn/calendar/api.html#lunar.festivals.html

2. 实现功能

2.1. 表单配置

在数据源处添加 solar2LunarResult 变量,用来存储转换的农历日期信息。

2.2. 在 didMount 函数中引入 lunar.js

将下列代码拷贝至 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. 配置公历日期转换农历信息函数

将下述代码拷贝至页面 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. 日期组件中使用

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

2.5. 将转换结果绑定至页面组件中

3. 实现效果

4. 在线试玩

Copyright © 2024钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4