
这段转换时间戳为 xxx 分钟前的函数在 firefox,chrome 浏览器中正常显示,在 ios 中出现错误 显示 NaN-NaN-NaN,为什么会出现这么奇怪的问题?
function getunix(timestamp, flag) { //timestamp 为时间戳,flag 为 ymd 时转为日期显示 否则显示 xxx 前 function zeroize(num) { return (String(num).length == 1 ? "0" :"") + num; } var curTimestamp = parseInt(new Date().getTime() / 1e3); //当前时间戳 var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数 var curDate = new Date(curTimestamp * 1e3); // 当前时间日期对象 var tmDate = new Date(timestamp * 1e3); // 参数时间戳转换成的日期对象 var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate(); var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds(); if (flag == "ymd") { var newDate = new Date((curTimestamp - 86400) * 1e3); // 参数中的时间戳加一天转换成的日期对象 return Y + "-" + zeroize(m) + "-" + zeroize(d); } if (timestampDiff < 60) { // 一分钟以内 return "现在"; } else if (timestampDiff < 3600) { // 一小时前之内 return Math.floor(timestampDiff / 60) + " min ago"; } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) { return "今天"; } else { var newDate = new Date((curTimestamp - 86400) * 1e3); // 参数中的时间戳加一天转换成的日期对象 if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) { return "昨天"; } else if (curDate.getFullYear() == Y) { return zeroize(m) + "-" + zeroize(d); } else { return Y + "-" + zeroize(m) + "-" + zeroize(d); } } } 1 nekoyaki 2018 年 12 月 12 日 我记得之前前端同事说过,好像 safari 的时间需要特殊处理,记不清细节了…… |
2 icebela 2018 年 12 月 21 日 这个有兼容问题,ios 上处理一下 new Date("2018-12-215 20:30:00".replace(/-/g,'/')).getTime()就可以了 |
3 e8c47a0d 2018 年 12 月 28 日 Safari 只支持 ISO8601 格式的时间字符串。(日期时间专家路过) |