1 //timestamp 时间戳 2 //option 格式(年月日 就输入YY-MM-DD 时分 就输入 hh-mm) 3 // 4 function formatDate(timestamp, option) { 5 6 var times = timestamp.replace("-", "/").replace("-", "/") 7 console.log(times) 8 var date = getDate(times); 9 var year = date.getFullYear(); 10 var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; 11 var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); 12 var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); 13 var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); 14 var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); 15 var over_time = year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds 16 //***至此以上是将时间2020-03-18T01:57:23.000+0000转为正常时间格式,以下为将时间进行增加8小时解决时区差异的操作*** 17 var time = getDate(Date.parse(over_time)); 18 time.setTime(time.setHours(time.getHours() + 8)); 19 20 //获取 年月日 21 if (option == ‘YY-MM-DD‘) return " " + year + "-" + month + "-" + day; 22 23 //获取年月 24 if (option == ‘YY-MM‘) return " " + year + "-" + month; 25 26 //获取年 27 if (option == ‘YY‘) return " " + year; 28 29 //获取月 30 if (option == ‘MM‘) return " " + month; 31 32 //获取日 33 if (option == ‘DD‘) return " " + day; 34 35 //获取昨天 36 if (option == ‘yesterday‘) return " " + day - 1; 37 38 //获取时分秒 39 if (option == ‘hh-mm-ss‘) return " " + hours + ":" + minutes + ":" + seconds; 40 41 //获取时分 42 if (option == ‘hh-mm‘) return " " + hours + ":" + minutes; 43 44 //获取分秒 45 if (option == ‘mm-ss‘) return minutes + ":" + seconds; 46 47 //获取分 48 if (option == ‘mm‘) return minutes; 49 50 //获取秒 51 if (option == ‘ss‘) return second; 52 53 //默认时分秒年月日 54 return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:‘ + minutes + ":" + seconds; 55 } 56 57 58 module.exports = { 59 formatDate: formatDate 60 }
ios端显示NaN的原因是:ios设备不支持new Date(time)的这个time格式为,即:yyyy-mm-dd。我们必须要转换成"/"格式。而wxs文件不支持new Date,所以我们需要使用getDate