JavaScript Date 对象 实现 时间戳=>日期对象 ,时间戳=>字符串,字符串=>时间戳,获取一年内所有的星期

由于业务需求要写一个日历,日历好写,但是,要标出周六和周日为红色,用到的部分核心函数如下:

<script>
        /*
       *时间戳=>日期对象
       * return Number
       * */
        function getDateObject(num) {
            return new Date(num);
        }
        /*
        *时间戳=>字符串
        * return Number
        * */
        function getString(num) {
            return new Date(num).getDay();
        }

        /*
        * 字符串=>时间戳
        * return String
        * */
        function getTimestamp(str) {
            return new Date(str).getTime();
        }
        /*
        * 获取一年内所有的星期
        * params String
        * return String
        * */
        function getWeek(year){
            //1天(d)=86400000毫秒(ms)
            var dayMseconds = 86400000;
            var year = year ||"2018";
            var firstDay = year + "-01-01";
            var lastDay = year + "-12-31";
            firstDay = getTimestamp(firstDay);
            lastDay = getTimestamp(lastDay);
            var resultArr = [];
            var result = [];
            for (var i = 0; i < 364; i++) {
                var day = getString(firstDay);
                if (day == 0 || day == 6) {
                    resultArr.push(firstDay)
                }
                firstDay += dayMseconds;
            }
            for (var j = 0; j < resultArr.length; j++) {
                var a = getDateObject(resultArr[j]).getFullYear() + '-' + (parseInt(getDateObject(resultArr[j]).getMonth()) + 1) + '-' + getDateObject(resultArr[j]).getDate();
                result.push(a)
            }
            return result;
        }
        console.log(getWeek(2019))
    </script>

 

posted @ 2018-09-25 10:42  奔跑的太阳花  阅读(681)  评论(0编辑  收藏  举报