在utils文件夹中,新建index.js文件。在新建的index.js文件中写入以下代码
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string')) {
if ((/^[0-9]+$/.test(time))) {
// support "1548221490638"
time = parseInt(time)
} else {
// support safari
// https://*.com/questions/4310953/invalid-date-in-safari
time = time.replace(new RegExp(/-/gm), '/')
}
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
return value.toString().padStart(2, '0')
})
return time_str
}
前端运用时,只需写如下代码
<script>
import { parseTime } from "@/utils";
export default {
},
</script>
接口传值使用案例如下:
getTaskCardExpireList() {
let dateTime = new Date();
dateTime = dateTime.setDate(dateTime.getDate() - 30);
dateTime = new Date(dateTime);
api_getTaskCardList({
creator: this.$store.state.user.id,
expireTimeStart: parseTime(dateTime, "{y}-{m}-{d} {h}:{i}:{s}"),
expireTimeEnd: parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
}).then((resp) => {
if (resp.success) {
this.zuijindaoqiTaskCardList = resp.entity;
}
});
},
页面显示后端时间数据案例如下:
<div class="profilePhoto">
<el-avatar
icon="el-icon-user-solid"
:src="item2.creatorAvatarUrl"
></el-avatar>
<span class="user">{{ item2.creatorName }}</span>
<span
style="float: right; margin-top: 6px; margin-right: 5px"
>{{ item2.dueDate | parseTime("{y}-{m}-{d}") }}</span
>
</div>