【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>

 

posted @ 2017-08-28 15:58  海绵小猪  阅读(474)  评论(0编辑  收藏  举报