zoukankan      html  css  js  c++  java
  • js解析格式化json日期

    代码:

    function jsonDateFormat(jsonDate) {//json日期格式转换为正常格式
        try {
            var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            var milliseconds = date.getMilliseconds();
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." +  milliseconds;
        } catch (ex) {
            return "";
        }
    }

    function formatTime(val) {
        var re = /-?d+/;
        var m = re.exec(val);
        var d = new Date(parseInt(m[0]));
        // 按【2012-02-13 09:09:09】的格式返回日期
        return d.format("yyyy/MM/dd hh:mm:ss");
    }

    Date.prototype.format = function (format) //author: meizz
    {
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(),    //day
            "h+": this.getHours(),   //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
            "S": this.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }


    /**
     * * 计算 两个时间 间隔的小时数
     * @param {} startDate
     * @param {} endDate
     * @returns {}
     */
    function GetDateDiff(startDate, endDate) {
        var startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
        var endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
        var dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60);
        return dates;
    }

    用法:

    var result =formatTime(json格式日期); 或者 jsonDateFormat(json格式日期)

  • 相关阅读:
    记一次百度面试题
    深度拷贝对象
    spring boot 学习笔记
    mac Zip 常用命令
    Mac OS 终端下使用 Curl 命令下载文件
    懒人必备的移动端定宽网页适配方案
    前端面试题之 sum(2)(3) (链式调用,toString,柯里化,数组操作)
    web上的复制
    fileupload上传文件时带参数
    Mac下Nginx环境配置
  • 原文地址:https://www.cnblogs.com/linJie1930906722/p/5210842.html
Copyright © 2011-2022 走看看