在JavaScript中将UNIX时间转换为mm/dd/yy hh:mm(24小时)

Mar*_*eek 4 javascript

我一直在用

timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());
Run Code Online (Sandbox Code Playgroud)

它将输出例如:

Tue Jul 6 08:47:00 CDT 2010
// 24小时

屏幕空间是主要的,所以我想占用更少的空间与日期和输出:

mm/dd/yy hh:mm
//也是24小时的时间

Mar*_*pel 11

只需在Date对象中添加一个额外的方法,就可以根据需要重复使用它.首先,我们需要定义一个辅助函数,String.padLeft:

String.prototype.padLeft = function (length, character) { 
    return new Array(length - this.length + 1).join(character || ' ') + this; 
};
Run Code Online (Sandbox Code Playgroud)

在此之后,我们定义Date.toFormattedString:

Date.prototype.toFormattedString = function () {
    return [String(this.getMonth()+1).padLeft(2, '0'),
            String(this.getDate()).padLeft(2, '0'),
            String(this.getFullYear()).substr(2, 2)].join("/") + " " +
           [String(this.getHours()).padLeft(2, '0'),
            String(this.getMinutes()).padLeft(2, '0')].join(":");
};
Run Code Online (Sandbox Code Playgroud)

现在,您可以像Date对象的任何其他方法一样使用此方法:

var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());
Run Code Online (Sandbox Code Playgroud)

但请记住,这种格式可能会令人困惑.例如,发行时

new Date().toFormattedString()
Run Code Online (Sandbox Code Playgroud)

该函数07/06/10 22:05此刻返回.对我而言,这更像是6月7日而不是7月6日.

编辑:仅当年份可以使用四位数字表示时才有效.在9999年12月31日之后,这将出现故障,您将不得不调整代码.

  • 这将在Y10K之后破裂.在那里,我说了. (15认同)
  • 修改标准对象是个坏主意。想想每个库都试图以自己的方式更改“日期”(以及使用其中多个库时的冲突)。只是不要这样做! (2认同)