2021-04-02
作者:互联网
前言
根据后台返回的日期,转化为今天,昨天,日期展示在前端的函数
可用于vue , uniapp , js , 原生微信小程序 项目使用中。
代码如下(示例):
formatDateIn(date, format) {
var formatDate = function(time, cFormat) {
if (!time) {
return
}
if (arguments.length === 0) {
return null;
}
var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
var date;
if (typeof time === 'object') {
date = time;
} else if (typeof time === 'string') {
var regTime = getRegExp('[-,年,月,日]', 'g');
time = time.replace(regTime, "/");
date = getDate(time);
} else {
if (typeof time === 'number') {
if ((time + '').length === 10) {
time = +time * 1000;
}
date = getDate(parseInt(time));
} else {
date = getDate(time);
}
}
var formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
var regFormat = getRegExp('{(y|m|d|h|i|s|a)+}', 'g');
var time_str = format.replace(regFormat, function (result, key) {
var value = formatObj[key];
if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
if (result.length > 0 && value < 10) {
value = '0' + value;
}
return value || 0;
});
return time_str;
}
var now = getDate();
var nowDay = getDate(formatDate(now, format));
var yesterday = Date.parse(nowDay) - (24 * 3600 * 1000);
// date = new Date(date);
if (formatDate(Date.parse(now), format) === formatDate(date, format)) {
return '今天';
} else if (formatDate(yesterday, format) === formatDate(date, format)) {
return '昨天'
} else {
return formatDate(date, format);
}
}
// js或者html调用
formatDateIn('2021-01-01 00:00:00','{y}-{m}-{d}')
// 日期转星期几
getWeek(dateString) {
if(dateString) {
let dateArray01 = dateString.split(" ")[0];
let dateArray02 = dateArray01.split("-");
let date = new Date(dateArray02[0], parseInt(dateArray02[1] - 1), dateArray02[2]);
return "周" + "日一二三四五六".charAt(date.getDay());
}
},
若果列表渲染,同一天日期有多个,循环列表记录是否第一次出现,页面中可根据v-if判断item.firstDate展示合并相同日期
let list = [] // 后台返回的数据
const markMap = {};
list .forEach((item, i) => {
const date = formatDate.formatDate(item.date, `{y}-{m}-{d}`);
if (markMap[date] === undefined) {
markMap[date] = i
item.firstDate = true;
}
})
欢迎评论点赞收藏哦
标签:02,return,04,format,formatDate,var,2021,time,date 来源: https://blog.csdn.net/weixin_43928043/article/details/115404739