1.看着时间显示有什么不同么?
显示规则:若为当天,则显示时分;若为其他日期,但是还在今年之内,显示月-日 时分;若为今年之前,则显示年-月-日 时分;
2.处理办法:
①直接在查询sql语句中将时间整理好,比如:
1 let questionsData = await this.model("questions").field('*,FROM_UNIXTIME(asktime,"%Y-%m-%d %H:%i") createtime,FROM_UNIXTIME(asktime,"%Y-%m-%d") createtime1,FROM_UNIXTIME(asktime,"%Y") createtime2,FROM_UNIXTIME(asktime,"%H:%i") createtime3,FROM_UNIXTIME(asktime,"%m-%d %H:%i") createtime4,FROM_UNIXTIME(replytime,"%Y-%m-%d %H:%i") createdate,FROM_UNIXTIME(replytime,"%Y-%m-%d") createdate1,FROM_UNIXTIME(replytime,"%Y") createdate2,FROM_UNIXTIME(replytime,"%H:%i") createdate3,FROM_UNIXTIME(replytime,"%m-%d %H:%i") createdate4').where({id:id}).find();//查询这条问答具体信息 2 3 let nowDatey = timeUtil.dateFormat(new Date().getTime() / 1000, 'yyyy-MM-dd'); 4 let nowDateyear = timeUtil.dateFormat(new Date().getTime() / 1000, 'yyyy'); 5 6 7 let asktime = questionsData.createtime;//提问时间 8 if(questionsData.createtime1==nowDatey){ 9 asktime=questionsData.createtime3; 10 }else if(questionsData.createtime2==nowDateyear){ 11 asktime=questionsData.createtime4; 12 }
不足:sql语句比较长,而且当查询数据量大的时候,这样写很耗费性能,不推荐;
②公共方法中处理时间:
1 let questionsData = await this.model("questions").where({id:id}).find();//查询这条问答具体信息 2 3 let asktime = timeUtil.dateFormat(questionsData.asktime, 'yyyy-MM-dd hh:mm');//提问时间 4 5 asktime = await this.questiontime(asktime); 6 7 8 //=====================时间格式化公共方法 9 /** 10 * 时间格式化 11 * parameters:formattime 12 * @returns {Promise<void>} 13 */ 14 questiontime = async function(formattime){ 15 let nowDate = new Date().getTime() / 1000; 16 if (timeUtil.dateFormat(formattime, 'yyyy-MM-dd') == timeUtil.dateFormat(nowDate, 'yyyy-MM-dd')) { 17 return formattime= timeUtil.dateFormat(formattime, 'hh:mm'); 18 } else if (timeUtil.dateFormat(formattime, 'yyyy') == timeUtil.dateFormat(nowDate, 'yyyy')) { 19 return formattime= timeUtil.dateFormat(formattime, 'MM-dd hh:mm'); 20 } else { 21 return formattime= timeUtil.dateFormat(formattime, 'yyyy-MM-dd hh:mm'); 22 } 23 }
这样处理的方法明显比第一种简洁、效率高。推荐使用。