微信小程序:获取当前日期(YYYY-mm-dd)_微信小程序获取当前时间
在微信小程序中获取当前日期并格式化为 yyyy-mm-dd
格式,可以通过以下代码实现:
方法
方法一:使用 JavaScript 的 Date
对象
function formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, \'0\'); // 月份从0开始,需要+1 const day = String(date.getDate()).padStart(2, \'0\'); return `${year}-${month}-${day}`;}// 获取当前日期const currentDate = new Date();const formattedDate = formatDate(currentDate);console.log(formattedDate); // 输出示例: \"2023-05-15\"
方法二:使用微信小程序的 getDate
API(更简单)
// 获取当前日期(兼容性更好)const now = new Date();const year = now.getFullYear();const month = (now.getMonth() + 1).toString().padStart(2, \'0\');const day = now.getDate().toString().padStart(2, \'0\');const formattedDate = `${year}-${month}-${day}`;console.log(formattedDate); // 输出示例: \"2023-05-15\"
在 Page 或 Component 中使用示例
Page({ data: { currentDate: \'\' }, onLoad() { this.setCurrentDate(); }, setCurrentDate() { const now = new Date(); const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \'0\')}-${String(now.getDate()).padStart(2, \'0\')}`; this.setData({ currentDate: formattedDate }); }})
WXML 中显示
当前日期:{{currentDate}}
关键点说明
getMonth()
返回 0-11,需要+1
padStart(2, \'0\')
确保单数月/日显示为05
而不是5
- 微信小程序完全支持标准 JavaScript 的
Date
对象,无需额外库