zoukankan      html  css  js  c++  java
  • javascript 日期月份加减

    项目中需要用到,自己写了一个。javascript日期按月加减

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            function dateToDate(date) {
                var sDate = new Date();
                if (typeof date == 'object'
                    && typeof new Date().getMonth == "function"
                    ) {
                    sDate = date;
                }
                else if (typeof date == "string") {
                    var arr = date.split('-')
                    if (arr.length == 3) {
                        sDate = new Date(arr[0] + '-' + arr[1] + '-' + arr[2]);
                    }
                }
    
                return sDate;
            }
    
    
            function addMonth(date, num) {
                num = parseInt(num);
                var sDate = dateToDate(date);
    
                var sYear = sDate.getFullYear();
                var sMonth = sDate.getMonth() + 1;
                var sDay = sDate.getDate();
    
                var eYear = sYear;
                var eMonth = sMonth + num;
                var eDay = sDay;
                while (eMonth > 12) {
                    eYear++;
                    eMonth -= 12;
                }
    
                var eDate = new Date(eYear, eMonth - 1, eDay);
    
                while (eDate.getMonth() != eMonth - 1) {
                    eDay--;
                    eDate = new Date(eYear, eMonth - 1, eDay);
                }
    
                return eDate;
            }
    
            function calcDate() {
                var d = document.getElementById('date').value;
                var n = document.getElementById('num').value;
                var eDate = addMonth(d, n);
                document.getElementById('result').innerHTML = eDate.getFullYear() + '-' + (eDate.getMonth() + 1) + '-' + eDate.getDate();
            }
        </script>
    </head>
    <body>
        <input type="date" id="date" />
        <input type="number" id="num" value="1" />
        <input type="button" value="计算" onclick="calcDate()" />
        <div id="result"></div>
    </body>
    </html>
  • 相关阅读:
    js传值到后台乱码问题
    js中string和json的相互转换
    js获取后台传给前台的值
    读取文件内容
    linux 的挂载问题
    php防止DDos攻击
    几个与特殊字符处理相干的PHP函数
    centos yum 安装nginx1.10
    linux centos6 yum php5.6
    linux mysql5.7 密码相关问题
  • 原文地址:https://www.cnblogs.com/lookforFree/p/4503656.html
Copyright © 2011-2022 走看看