定义一个common.js文件,放自定义的格式化函数
一、数量格式化
//数量格式化
export function formatNum(num) {
return num >= 1e3 && num < 1e4 ? (num / 1e3).toFixed(1) + 'k' : num >= 1e4 ? (num / 1e4).toFixed(1) + 'w' : num;
}
二、日期格式化
1、时间戳转化为时间格式
export function formatTime(value, type = 0) {
var time = new Date(value);
var year = time.getFullYear();
var month = time.getMonth() + 1;
var date = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
month = month < 10 ? "0" + month : month;
date = date < 10 ? "0" + date : date;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
var arr = [
year + "-" + month + "-" + date,
year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second,
year + "年" + month + "月" + date,
year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second,
hour + ":" + minute + ":" + second,
month + "-" + date,
year + "/" + month + "/" + date + " " + hour + ":" + minute
]
// 设置返回的时间格式,type代表返回对应数组下标的格式,不传type默认返回第一种格式
return arr[type];
}
三、引用自定义格式化函数
onLoad: function () {
// 将时间戳改为可读日期模式
let newarr = [
{
title:'红茶',
author:"虾子",
time:1672486225000,
num:'9999'
},
{
title:'绿茶',
author:"摩托",
time:1672445597000,
num:'100000'
},
{
title:'青山不改,绿水长流,夏天依然热烈',
author:"果子",
time:1672390386000,
num:'23'
},
]
newarr.forEach(item => {
item.num = formatNum(item.num)
item.time = formatTime(item.time)
// item.time = formatTime(item.time,1)
})
// console.log(newarr);
this.setData({
newsArr:newarr
})
},