我们用 JavaScript 中的当前日期时间创建一个 today 对象。
let today = new Date()
console.log(today) // Wed May 05 2021 15:31:36 GMT+0800 (中国标准时间)
使用 Date
对象的内置 getMonth
方法获取当前月份作为值。
let moonLanding = today.getMonth()
console.log(moonLanding) // 4
如果你想得到月份名称,可以自定义一个方法:
const getMonthName = (val) => {
const month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
return month[val]
}
console.log(getMonthName(moonLanding)) // "May"
也可以使用 switch
,你觉得怎么优雅怎么来吧。