推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
allinoneok

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

  •  
  •   allinoneok · Dec 12, 2018 · 4749 views
  •   You need to sign in to view this topic
    This topic created in 2902 days ago, the information mentioned may be changed or developed.

    这段转换时间戳为 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 replies  •  2018-12-28 15:36:33 +08:00
    nekoyaki
    nekoyaki
    Dec 12, 2018
    1
    我记得之前前端同事说过,好像 safari 的时间需要特殊处理,记不清细节了……
    icebela
    icebela
    Dec 21, 2018
    2
    这个有兼容问题,ios 上处理一下 new Date("2018-12-215 20:30:00".replace(/-/g,'/')).getTime()就可以了
    e8c47a0d
    e8c47a0d
    Dec 28, 2018
    3
    Safari 只支持 ISO8601 格式的时间字符串。(日期时间专家路过)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   862 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 20:08 · PVG 04:08 · LAX 12:08 · JFK 15:08
    ♥ Do have faith in what you're doing.