微信小程序:获取当前日期(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 中显示

<view>当前日期:{{currentDate}}</view>

关键点说明

  1. getMonth() 返回 0-11,需要 +1
  2. padStart(2, '0') 确保单数月/日显示为 05 而不是 5
  3. 微信小程序完全支持标准 JavaScript 的 Date 对象,无需额外库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

25号底片~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值