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

一、直接使用方式

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

复制代码
//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
    });
  }
 
})

示例

相关推荐
说私域11 小时前
链动2+1模式AI智能名片S2B2C商城小程序中电商直播的应用机制与价值创新研究
人工智能·小程序
虾..15 小时前
Linux 进程池小程序
linux·c++·小程序
Coder_Boy_15 小时前
【人工智能应用技术】-基础实战-小程序应用(基于springAI+百度语音技术)智能语音控制
人工智能·小程序
计算机毕设指导615 小时前
基于微信小程序的垃圾分类信息系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
kaka-33317 小时前
微信小程序中使用 xlsx(xlsx.mini.min.js)实现 Excel 导入导出功能
javascript·微信小程序·excel
Coder_Boy_18 小时前
【人工智能应用技术】-基础实战-小程序应用(基于springAI+百度语音技术)智能语音控制-单片机交互
人工智能·单片机·小程序
Coder_Boy_19 小时前
【人工智能应用技术】-基础实战-小程序应用(基于springAI+百度语音技术)智能语音开关
人工智能·百度·小程序
说私域2 天前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的社群初期运营策略研究
人工智能·小程序
计算机毕设指导62 天前
基于微信小程序的校园物品租赁与二手交易系统【源码文末联系】
spring boot·mysql·微信小程序·小程序·tomcat·maven·intellij-idea
科技小金龙2 天前
小程序/APP接入分账系统:4大核心注意事项,避开合规与技术坑
大数据·人工智能·小程序