• 时间戳判断问题


    JS获取当前时间戳的方法-JavaScript 获取当前毫秒时间戳有以下三种方法:  
    
    var timestamp =Date.parse(new Date());    结果:1280977330000       //不推荐; 毫秒改成了000显示  
    
    var timestamp =(new Date()).valueOf();       结果:1280977330748       //推荐;   
    
    var timestamp=new Date().getTime();         结果:1280977330748        //推荐;   
    
    
    js中单独调用new Date();  显示这种格式  Mar 31 10:10:43 UTC+0800 2012  
    
    但是用new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数  
    function timestampFormat( timestamp ) {
        var curTimestamp = new Date().getTime(); //当前时间戳
        // console.log(curTimestamp);
        var Diff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
    
        var curDate = new Date( curTimestamp); // 当前时间日期对象
        var tmDate = new Date( timestamp);  // 参数时间戳转换成的日期对象
    
        var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
        var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();
    
        if ( Diff < 60*1000 ) { // 一分钟以内
            return "刚刚";
        } else if( Diff < 3600*1000 ) { // 一小时前之内
            return Math.floor( Diff / (60*1000 )) + "分钟前";
        } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
            return Math.floor( Diff / (60*60*1000 )) + "小时前";
        } else {
            var newDate = new Date( (curTimestamp - 86400*1000)); // 参数中的时间戳加一天转换成的日期对象
            if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
            return  '一天前';
            } else if (Diff>86400*1000*2){
               return new Date(timestamp);
            }
        }
    }
    console.log(timestampFormat(1557930299182)) //2012年01月10日 12:46
    console.log(timestampFormat(1557930200000)) //刚刚
    console.log(timestampFormat(Date.parse('2016-10-11 15:10:10'))) //16分钟前
    console.log(timestampFormat(Date.parse('2016-10-11 10:10:10')))//今天10:10
    console.log(timestampFormat(Date.parse('2016-10-10 10:10:10'))) //昨天10:10
    console.log(timestampFormat(Date.parse('2016-02-10 10:10:10'))) //02月10日 10:10
    console.log(timestampFormat(Date.parse('2012-10-10 10:10:10'))) //2012年10月10日 10:10
  • 相关阅读:
    个人WPF快速入门笔记 基础样式篇02
    个人WPF快速入门笔记 基础布局篇01
    nginx常用笔记备忘
    【leetcode】1685. Sum of Absolute Differences in a Sorted Array
    【leetcode】1696. Jump Game VI
    【leetcode】1694. Reformat Phone Number
    【leetcode】1684. Count the Number of Consistent Strings
    【leetcode】1695. Maximum Erasure Value
    【leetcode】1671. Minimum Number of Removals to Make Mountain Array
    【leetcode】1689. Partitioning Into Minimum Number Of DeciBinary Numbers
  • 原文地址:https://www.cnblogs.com/sarah-wen/p/10872629.html
Copyright © 2020-2023  润新知