美文网首页
按类型格式化日期

按类型格式化日期

作者: ee03052cdf84 | 来源:发表于2020-09-18 15:09 被阅读0次

    按类型格式化日期

    关于更多日常使用的公共类的操作方法,可以关注下小滑轮网站 http://www.feiaci.com/#/self/code

    按类型格式化日期

    /**
     * 按类型格式化日期
     * @param {*} date 具体日期变量
     * @param {string} dateType 需要返回类型,包括('yyyy年mm月dd日','yyyy-mm-dd',
     *  'yyyy.mm.dd','yyyy-mm-dd MM:mm:ss', 'mm-dd MM:mm:ss', 'yyyy年mm月dd日 MM:mm:ss')
     * @return {string} dateText 返回为指定格式的日期字符串
     */
    function getFormatDate(date, dateType) {
        let dateObj = new Date(date);
        let month = dateObj.getMonth() + 1;
        let strDate = dateObj.getDate();
        let hours = dateObj.getHours();
        let minutes = dateObj.getMinutes();
        let seconds = dateObj.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
    
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds
        }
    
        let dateText = dateObj.getFullYear() + '年' + (dateObj.getMonth() + 1) + '月' + dateObj.getDate() + '日';
        if (dateType == "yyyy-mm-dd") {
            dateText = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dateObj.getDate();
        }
        if (dateType == "yyyy.mm.dd") {
            dateText = dateObj.getFullYear() + '.' + (dateObj.getMonth() + 1) + '.' + dateObj.getDate();
        }
        if (dateType == "yyyy-mm-dd MM:mm:ss") {
            dateText = dateObj.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds;
        }
        if (dateType == "mm-dd MM:mm:ss") {
            dateText = month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds;
        }
        if (dateType == "yyyy年mm月dd日 MM:mm:ss") {
            dateText = dateObj.getFullYear() + '年' + month + '月' + strDate + '日' + ' ' + hours + ":" + minutes + ":" + seconds;
        }
        return dateText;
    }
    

    还有更多的日期操作:设置几天后的日期,获取当前时间的n天后的时间戳, 本周第一天, 本月最后一天, 星期转换,将数字转换成英文等等。可以在小滑轮网站(http://www.feiaci.com/#/self/code)找到

    相关文章

      网友评论

          本文标题:按类型格式化日期

          本文链接:https://www.haomeiwen.com/subject/wxjjyktx.html