在小程序,想要实现自动更新是哪个月份,并且是用英文表示可以怎么实现呢?
有三种方法可以实现,具体如下
第一种:使用数组
1.在data中定义一个变量currentMonthInEnglish,用于存放当前月份的英文
2.定义一个数组monthNames,在数组里放入1-12月的英文
3.因为使用date的getmonth函数获取当前月份也是从0开始的,所以可以直接monthNames[now.getMonth()]
4.进行挂载
具体实现代码如下
<script>
export default {
data() {
return {
currentMonthInEnglish: '',
};
},
methods: {
formatDate() {
const now = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const month = monthNames[now.getMonth()];
this.currentMonthInEnglish = month;
},
},
mounted() {
this.formatDate();
}
}
</script>
第二种:使用switch
1.先定义一个变量e_month接收当前月份
2.定义变量获取getMonth函数所获取的当前月份
3.编写switch,用于根据当前是哪个月,就给e_month写入哪个月份的英文,也一样记得方法的挂载
具体实现代码如下
data() {
e_month:""
}
methods: {
// 月份英文
get_E_month(){
const now = new Date();
const currentMonth = now.getMonth() + 1;
// 输出1-12月英文
switch(currentMonth){
case 1:
this.e_month="January";
break;
case 2:
this.e_month="February";
break;
case 3:
this.e_month="March";
break;
case 4:
this.e_month="April";
break;
case 5:
this.e_month="May";
break;
case 6:
this.e_month="June";
break;
case 7:
this.e_month="July";
break;
case 8:
this.e_month="August";
break;
case 9:
this.e_month="September";
break;
case 10:
this.e_month="October";
break;
case 11:
this.e_month="N0vember";
break;
case 12:
this.e_month="December";
break;
}
return currentMonth;
}
}
第三种:直接获取英文,但前提是使用的系统是英文模式
具体代码如下
export default {
data() {
return {
currentDate: '',
};
},
onLoad() {
this.getCurrentDate();
},
methods: {
getCurrentDate() {
const now = new Date();
const month = now.toLocaleString('en-US', { month: 'long' }); // 获取月份的英文
this.currentDate = month
},
},
};