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

一、直接使用方式

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

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

示例

相关推荐
计算机毕设指导61 天前
基于微信小程序的奶茶店点餐系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
2501_915918411 天前
Mac 抓包软件有哪些?Charles、mitmproxy、Wireshark和Sniffmaster哪个更合适
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
iOS 抓包绕过 SSL 证书认证, HTTPS 暴力抓包、数据流分析
android·ios·小程序·https·uni-app·iphone·ssl
2501_915921431 天前
iOS App 电耗管理 通过系统电池记录、Xcode Instruments 与克魔(KeyMob)组合使用
android·ios·小程序·https·uni-app·iphone·webview
数字游民95271 天前
2小时VibeCoding了一个看图猜词小程序:猜对了么
人工智能·ai·小程序·ai绘画·数字游民9527
qq_12498707532 天前
基于小程序中医食谱推荐系统的设计(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·计算机毕业设计
2501_915918412 天前
iOS App 测试方法,Xcode、TestFlight与克魔(KeyMob)等工具组合使用
android·macos·ios·小程序·uni-app·iphone·xcode
棒棒的唐2 天前
微信小程序右上角分享按钮如何根据用户登录状态确定是否允许分享
微信小程序·小程序
2501_915921432 天前
iOS 描述文件制作过程,从 Bundle ID、证书、设备到描述文件生成后的验证
android·ios·小程序·https·uni-app·iphone·webview
小白学大数据2 天前
基于 Python 的知网文献批量采集与可视化分析
开发语言·爬虫·python·小程序