1、根据日期信息返回对应的星座

在表单信息根据“出生年月”自动填充星座,表单需求效果如下截图所示:

编写的前端脚本代码,如下所示:


 //加载事件
 onLoad:function(form){
    form.$refs.dynamicForm.$watch('models.birthDate',(data)=>{
      debugger
        const today = new Date(data);
        const month = today.getMonth() + 1; // getMonth() 返回 0-11,需加1
       const day = today.getDate();
       form.setData('constellation', this.getZodiacSign(month, day))
       console.info(this.getZodiacSign(month, day))
     })
  },

//根据日期获取星座 
 getZodiacSign(month, day){
      // 星座数组,包含每个星座的起始月份、起始日期和星座名称
    const signs = [
        { month: 1, day: 20, name: '水瓶座' },
        { month: 2, day: 19, name: '双鱼座' },
        { month: 3, day: 21, name: '白羊座' },
        { month: 4, day: 20, name: '金牛座' },
        { month: 5, day: 21, name: '双子座' },
        { month: 6, day: 22, name: '巨蟹座' },
        { month: 7, day: 23, name: '狮子座' },
        { month: 8, day: 23, name: '处女座' },
        { month: 9, day: 23, name: '天秤座' },
        { month: 10, day: 24, name: '天蝎座' },
        { month: 11, day: 23, name: '射手座' },
        { month: 12, day: 22, name: '摩羯座' }
    ];
   // 遍历星座数组判断
    for (let i = 0; i < signs.length; i++) {
        const sign = signs[i];
        // 如果月份大于当前星座的月份,直接匹配当前星座
        if (month > sign.month) {
            return sign.name;
        }
        // 如果月份等于当前星座的月份且日期大于等于起始日期,匹配当前星座
        else if (month === sign.month && day >= sign.day) {
            return sign.name;
        }
    }

    // 若以上都不匹配,则为最后一个星座(摩羯座)
    return '摩羯座';
 }
作者:黄春艳  创建时间:2025-11-07 17:51
最后编辑:黄春艳  更新时间:2025-11-28 15:39