V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
allinoneok
V2EX  ›  JavaScript

js 时间戳转换在 ios 中出现错误

  •  
  •   allinoneok · 2018-12-12 14:34:43 +08:00 · 3307 次点击
    这是一个创建于 1933 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这段转换时间戳为 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);
            }
        }
    }
    
    3 条回复    2018-12-28 15:36:33 +08:00
    nekoyaki
        1
    nekoyaki  
       2018-12-12 16:18:29 +08:00
    我记得之前前端同事说过,好像 safari 的时间需要特殊处理,记不清细节了……
    icebela
        2
    icebela  
       2018-12-21 10:12:37 +08:00
    这个有兼容问题,ios 上处理一下 new Date("2018-12-215 20:30:00".replace(/-/g,'/')).getTime()就可以了
    e8c47a0d
        3
    e8c47a0d  
       2018-12-28 15:36:33 +08:00
    Safari 只支持 ISO8601 格式的时间字符串。(日期时间专家路过)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5232 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 01:25 · PVG 09:25 · LAX 18:25 · JFK 21:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.