微信小程序获取当前日期时间

一、直接使用方式

在小程序中获取当前系统日期和时间,可直接拿来使用的常用的日期格式

复制代码
//1. 当前日期  YYYY-MM-DD

new Date().toISOString().substring(0, 10)

new Date().toJSON().substring(0, 10)


//2. 当前日期  YYYY/MM/DD

new Date().toLocaleDateString()

//3. 当前时间  HH:mm:ss    
new Date().toTimeString().substring(0,8)
 
 //4. 当前日期时间  YYYY-MM-DD HH:mm:ss    
new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8)

二、封装utils方式

2.1 utils代码

复制代码
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
 
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
 
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
 
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
//此处声明几个方法就写几个,如上面定义了formatTime 写法如下
module.exports = {
  formatTime: formatTime 
}

一般放入utils工具类

2.2 utils调用

参考代码

复制代码
// 在需要使用的js文件中,导入js
var util = require('../../utils/util.js');
Page({
  data: {
 
  },
  onLoad: function () {
    // 调用函数时,传入new Date()参数,返回值是日期和时间
    let time = util.formatTime(new Date());
    // 再通过setData更改Page()里面的data,动态更新页面的数据
    this.setData({
      time: time
    });
  }
 
})

示例

相关推荐
咖啡八杯5 小时前
微信小程序人脸认证1.0迁移2.0
后端·微信小程序
xshirleyl5 小时前
微信小程序开发week8-慕尚花坊项目
微信小程序·小程序
admin and root8 小时前
Claude+Trae大模型 配置Chrome MCP联动Yakit自动化渗透测试
微信小程序·渗透测试·自动化·攻防演练·ai安全·claude code·ai自动化渗透测试
code_li20 小时前
小程序上线需要的资质证书汇总
小程序·上线·发布·资质
hnxaoli1 天前
统信小程序(十三)循环键鼠操作程序
python·小程序
i查拉图斯特拉如是1 天前
使用workbuddy 30分钟搭建微信小程序
微信小程序·小程序
IceSugarJJ1 天前
Open-AutoGLM项目学习
语言模型·微信小程序·github
2501_916008891 天前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
android·macos·ios·小程序·uni-app·iphone·webview
咖啡の猫1 天前
小程序协同工作和发布
小程序
维双云1 天前
小程序怎么制作工具?与其盲目找开发,不如先分清自己要哪一种
小程序