JavaScript:上次修改日期从24小时到12小时

时间:2014-06-07 13:44:11

标签: javascript

亲爱的JavaScript专家:

我想知道是否有办法在上次修改日期的JavaScript代码中更改小时格式。这是我到目前为止的代码:

<script type="text/javascript">
document.write("This page was last modified on: " + document.lastModified +"");
</script>

非常感谢任何帮助。我是JavaScript和Stack Overflow的新手,所以我很高兴问我的第一个问题。

谢谢,

Michael K。

1 个答案:

答案 0 :(得分:0)

我只能想到手动执行:http://jsfiddle.net/ex9T7/

alert(formatDate(document.lastModified))


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);
}