【发布时间】:2022-01-14 16:20:55
【问题描述】:
我用koajs写了一个webapp,数据库中的时间戳格式有点问题,记录很多,每条记录都是这样的格式。
{
"_id": {
"$oid": "61df7c96d649ac83eefa36d3"
},
"key": 1286756906,
"status": 1,
"name": "bill",
"starttime": 1642068153784,
"endtime": 1673604153784
}
我需要在前端显示starttime 和endtime,格式类似于2022-01-03 10:10:10。
-
我应该将时间戳格式化过程放在哪里?前端还是后端?
-
我目前的解决方案是后端,如下所示
list.js
.get("/list", async (ctx) => {
let allrecords = await db.myrecords.find();
await ctx.render("list", {
allrecords: allrecords.map(d => { d.endtime = new Date(d.endtime).getFullYear() + "-" + (new Date(d.endtime).getMonth()+1 < 10? '0'+ (new Date(d.endtime).getMonth()+1):(new Date(d.endtime).getMonth()+1)) + "-" + new Date(d.endtime).getDate() + " " + new Date(d.endtime).getHours() + ":" + (new Date(d.endtime).getMinutes()< 10 ? '0' + new Date(d.endtime).getMinutes():new Date(d.endtime).getMinutes()); return d}).map(d => { d.starttime = new Date(d.starttime).getFullYear() + "-" + (new Date(d.starttime).getMonth()+1 < 10? '0'+ (new Date(d.starttime).getMonth()+1):(new Date(d.starttime).getMonth()+1)) + "-" + new Date(d.starttime).getDate() + " " + new Date(d.starttime).getHours() + ":" + (new Date(d.starttime).getMinutes()< 10 ? '0' + new Date(d.starttime).getMinutes():new Date(d.starttime).getMinutes()); return d})
});
})
list.ejs
<% allrecords.forEach(function(item, i){%>
<div class="item">
<div>start: <%=item.starttime%></div>
<div>end: <%=item.endtime%></div>
</div>
<%})%>
我觉得这个解决方案效率太低了,有没有其他有效的解决方案?
谢谢。
【问题讨论】: