zoukankan      html  css  js  c++  java
  • 【js Date】时间字符串、时间戳转换成今天,明天,本月等文字日期

    作为前端开发攻城师,难免对时间进行各种计算和格式转换,一个js的Date对象统统可以搞定。
    下例是将一个具体的时间转换成今天、明天、几天之内、本月等文字描述的日期的工具函数,也可以基于它扩展,多应用于网络资源(如影视动画)的上映场景中。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>changeDate</title>
    </head>
    <body>
    
    </body>
    <script>
    
        //工具类
        var Util = {
            /**
             * 根据日期字符串获取即将上映文字描述
             * 返回值:
             * 明天上映;
             * 后天上映;
             * 七天之内上映;
             * 本月上映;
             * 其他(普通日期)
             */
            getShowDate : function(strTime){
                //上映日期
                var showDateObj = new Date(strTime),
                    showDateTimeStamp = Date.parse(strTime); 
                //今天
                var nowDate = new Date(), 
                    Y = nowDate.getFullYear() + '-',
                    M = (nowDate.getMonth()+1 < 10 ? '0'+(nowDate.getMonth()+1) : nowDate.getMonth()+1) + '-',
                    D = nowDate.getDate();
                var todayTimeStamp = Date.parse(Y + M + D + ' 00:00:00');
    
                //上映日期与今天时间差
                var days = Math.ceil((showDateTimeStamp-todayTimeStamp)/(1000*60*60*24));
    
                var result = strTime.substring(0,10) + '上映'; //默认取日期
                if(days > 0){
                    if(days == 1){
                        result = '今天上映';
                    } else if(days == 2){
                        result = '明天上映';
                    } else if(days < 8 ){
                        result = days + '天内上映';
                    } else if(showDateObj.getFullYear() == nowDate.getFullYear()
                                && showDateObj.getMonth() == nowDate.getMonth()){
                        result = '本月上映';
                    }
                }
    
                return result;
            }
        }
    
        window.onload = function(){
            var result = Util.getShowDate('2017-08-29 00:00:49'); 
            console.log(result);
        } 
    </script>
    </html>
  • 相关阅读:
    C语言结构体+公用体+枚举训练
    TIFF图像文件格式详解
    Professional CUDA C Programming的代码实例1.1
    C语言数组强化训练
    C语言字符数组与字符串
    文件操作
    MATLAB 与Modelsim之间对测试系统的联合仿真
    FFT实现逆FFT
    眼图——概念与测量(摘记)
    《我的心曾悲伤七次》卡里·纪伯伦
  • 原文地址:https://www.cnblogs.com/feitan/p/7444245.html
Copyright © 2011-2022 走看看