I use koajs to wrote a webapp and I'm having a little trouble with the timestamp format in the database, there are a lot of records and each record is formatted like this.
{
"_id": {
"$oid": "61df7c96d649ac83eefa36d3"
},
"key": 1286756906,
"status": 1,
"name": "bill",
"starttime": 1642068153784,
"endtime": 1673604153784
}
I need to show starttime and endtime on the front-end in format like 2022-01-03 10:10:10.
Where should I put the timestamp formatting process on? The front-end or the back-end?
My current solution is the back-end, like following
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 >
<div>start: <%=item.starttime%></div>
<div>end: <%=item.endtime%></div>
</div>
<%})%>
I find this solution too inefficient, is there any other efficient solution?
Thank you.
CodePudding user response:
Doing it on server side is fine, if you only need those time values as strings on client side. For the mapping I would do:
.get("/list", async (ctx) => {
let allrecords = await db.myrecords.find();
await ctx.render("list", {
allrecords: allrecords.map(d => {
d.endtime = new Date(d.endtime).toISOString().
.replace('T', ' ').substr(0, 19);
d.starttime = new Date(d.starttime).toISOString().
.replace('T', ' ').substr(0, 19);
return d
});
});
})
Then you are creating each of your dates only one single time.
