更改日期格式功能

时间:2016-02-12 09:50:29

标签: javascript jquery function date

我正在尝试更改日期格式,请您帮助我将日期格式更改为2016年2月12日星期一11:00?

以下是代码:

function nicetime(a, out) {
    var d = Math.round((+new Date - a) / 1000),
        fuzzy = '',
        n = 'mins',
        d = d < 0 ? 0 : d;
    if (out == 1) {
        return d;
    } else if (out == 0) {
        var chunks = new Array();
        chunks[0] = [60 * 60 * 24 * 365, 'year', 'years'];
        chunks[1] = [60 * 60 * 24 * 30, 'month', 'months'];
        chunks[2] = [60 * 60 * 24 * 7, 'week', 'weeks'];
        chunks[3] = [60 * 60 * 24, 'day', 'days'];
        chunks[4] = [60 * 60, 'hr', 'hrs'];
        chunks[5] = [60, 'min', 'mins'];
        var i = 0,
            j = chunks.length;
        for (i = 0; i < j; i++) {
            s = chunks[i][0];
            if ((xj = Math.floor(d / s)) != 0) {
                n = xj == 1 ? chunks[i][1] : chunks[i][2];
                break;
            }
        }
        fuzzy += xj == 1 ? '1 ' + n : xj + ' ' + n;
        if (i + 1 < j) {
            s2 = chunks[i + 1][0];
            if (((xj2 = Math.floor((d - (s * xj)) / s2)) != 0)) {
                n2 = (xj2 == 1) ? chunks[i + 1][1] : chunks[i + 1][2];
                fuzzy += (xj2 == 1) ? ' + 1 ' + n2 : ' + ' + xj2 + ' ' + n2;
            }
        }
        fuzzy += ' ago';
        return fuzzy;
    }
}

1 个答案:

答案 0 :(得分:0)

假设您的日期是“2011年2月4日19:00:00”

function formatDate(date) {
 var d = new Date(date);
 var hh = d.getHours();
 var m = d.getMinutes();
 var s = d.getSeconds();
 var dd = "AM";
 var h = hh;
 if (h >= 12) {
    h = hh-12;
    dd = "PM";
 }
 if (h == 0) {
    h = 12;
 }
 m = m<10?"0"+m:m;

 s = s<10?"0"+s:s;

/* if you want 2 digit hours:
 h = h<10?"0"+h:h; */

 var pattern = new RegExp("0?"+hh+":"+m+":"+s);

 var replacement = h+":"+m;
/* if you want to add seconds
 replacement += ":"+s;  */
 replacement += " "+dd;    

 return date.replace(pattern,replacement);
}

alert(formatDate("February 04, 2011 12:00:00"));