您的位置:首页 > 游戏 > 游戏 > 中国香烟网上商城_网络工作室门店照片_搜索引擎名词解释_成都网站快速优化排名

中国香烟网上商城_网络工作室门店照片_搜索引擎名词解释_成都网站快速优化排名

2025/4/24 6:42:48 来源:https://blog.csdn.net/weixin_46001736/article/details/146804885  浏览:    关键词:中国香烟网上商城_网络工作室门店照片_搜索引擎名词解释_成都网站快速优化排名
中国香烟网上商城_网络工作室门店照片_搜索引擎名词解释_成都网站快速优化排名

在微信小程序中获取当前日期并格式化为 yyyy-mm-dd 格式,可以通过以下代码实现:

方法

方法一:使用 JavaScript 的 Date 对象

function formatDate(date) {const year = date.getFullYear();const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要+1const 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 对象,无需额外库

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com