前端获取到的数据是这样的:2023-04-04 16:32:00,我怎么把年月日截去,只留取当天时间来进行显示
可以直接使用js的date吧
const date = new Date(“2023-04-04 16:32:00”);
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
直接这样就可以
let a = '2023-04-04 16:32:00'
a.split(' ')[1] // 注意中间空格
用split(), 仅供参考
这也太简单了吧!
let time = '2023-04-04 16:32:00'
return time.split(' ')[1] // 注意中间空格 取数组第二个值
不知道你这个问题是否已经解决, 如果还没有解决的话:实现效果(没加样式)
1:准备好要获取时间的.js文件中加载util.js文件,文件目录中有默认的代码
util.js
const formatTime =date=>{
const year= date.getFullYear()
const month=date.getMonth()+1
const day=date.getDate()
const hour=date.getHours()
const minute=date.getMinutes()
const second = date.getSeconds()
return [year,month,day].map(formatNumber).join('/')+' '+[hour,minute,second].map(formatNumber).join(':')
}
const formatNumber = n =>{
n=n.toString()
return n[1]?n : '0'+n
}
module.exports = {
formatTime:formatTime
}
2.展示的页面
wxml
<view>{{time[0]}}-{{time[1]}}-{{time[2]}}</view>
3.展示页面的js
js
var util = require('../../utils/util.js');
Page({
data: {
},
onLoad: function () {
// 调用函数时,传入new Date()参数,返回值是日期和时间
var time = util.formatTime(new Date());
// 再通过setData更改Page()里面的data,动态更新页面的数据
this.setData({
time: time
});
}
})
4.对时间切片
time=time.split(" ")[0].split("/")//变数组
console.log(time)
切片效果
// 获取当前时间的 Date 对象
const currentDate = new Date();
// 从 Date 对象中获取小时、分钟和秒数
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();
// 将小时、分钟和秒数转换为字符串,并在需要时添加前导零
const displayHours = hours < 10 ? "0" + hours : hours;
const displayMinutes = minutes < 10 ? "0" + minutes : minutes;
const displaySeconds = seconds < 10 ? "0" + seconds : seconds;
// 将时间字符串拼接起来,以创建完整的时间字符串
const displayTime = displayHours + ":" + displayMinutes + ":" + displaySeconds;
// 将时间字符串显示在您的页面上
console.log(displayTime);