封装 - 日期的获取以及格式转换

1、获取当天所在的年份

  function getYear () {
        let mydate = new Date();
        let value = mydate.getFullYear();
        return value;
    }

2、获取当天所在的月数

 function getMonth () {
        let mydate = new Date();
        let value = mydate.getMonth() + 1;
        return value;
    }

3、获取当天所在的号数

function getDate () {
    let mydate = new Date();
    let value = mydate.getDate();
    return value;
}

4、获取天数

 function getDates(year, month) {
        let dates = new Date(year, month, 0).getDate();
        return dates;
    }

5、日期格式转化1    2018,1->2018/01

  function formatDating(year, month, date) {
        month = fn.addZero(month);
        if (date) {
            date = fn.addZero(date);
        }
        return year + '/' + month + (date ? '/' + date : '');
    }

6、日期格式转化2    2018,1->2018年01

 function formatDating2(year, month, date) {
        let mon = month.toString();
        if (mon.length < 2 && month < 10) {
            month = fn.addZero(month);
        }
        if (date) {
            let dat = date.toString();
            if (dat.length < 2 && date < 10) {
                date = fn.addZero(date);
            }
        }
        return year + '年' + month + '月' + (date ? date + '日' : '');
    }

7、年份

function getyears() {
    let arr = [];
    for (var i = 2000; i < 2030; i++) {
        arr.push({
            name: i,
            value: i
        })
    }
    return arr;
}

8、月份

 function getmonths() {
        let arr = [];
        for (var i = 1; i <= 12; i++) {
            arr.push({
                name: i,
                value: i
            })
        }
        return arr;
    }

9、日期格式定向转化 2018/01->2018年01月,2018/01/01->2018年01月01日

  function cToe(str, type, ind) {
        let restr = ''
        str = str.toString();
        if (ind) {
            type = type == -1 || type == 2 ? type : type + 1
        }

        if (type == 0 || type == 3) {
            //日+自定义   2018/01/01
            restr = str.substring(0, 4) + '/' + str.substring(5, 7) + '/' + str.substring(8, 10) + '';
        }
        else if (type == 1) {
            //月     2018/01
            restr = str.substring(0, 4) + '/' + str.substring(5, 7) + '';
        }
        else if (type == 2) {
            //季度   2018 第一季度
            restr = str.substring(0, 4) + ' ' + str.substring(5, str.length);
        }
        else if (type == -1) {
            //年份
            str = str.toString();
            restr = str.substring(0, str.length);
        }
        return restr;
    }

10、处理年月的格式

function tochinesedate(params, type) {
    let arr = params.split(type);
    let time = arr[0] + '年' + arr[1] + '月';
    return time;
}
发布了44 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/LiaoFengJi/article/details/98588439