在JavaScript中将UNIX时间转换为mm / dd / yy hh:mm(24小时) [英] Convert UNIX Time to mm/dd/yy hh:mm (24 hour) in JavaScript

查看:66
本文介绍了在JavaScript中将UNIX时间转换为mm / dd / yy hh:mm(24小时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用

timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());

它会输出例如:

Tue Jul 6 08:47:00 CDT 2010

// 24小时时间

Tue Jul 6 08:47:00 CDT 2010
//24 hour time

屏幕房地产是素数,所以我想采取使用日期和输出减少空间:

Screen real estate is prime, so I would like to take up less space with the date and output:

mm / dd / yy hh:mm

//也是24小时时间

mm/dd/yy hh:mm
//also 24 hour time

推荐答案

只需在 Date 对象中添加一个额外的方法,这样就可以重复使用它了如你所愿。首先,我们需要定义一个辅助函数, String.padLeft

Just add an extra method to the Date object, so you can reuse it as much as you want. First, we need to define a helper function, String.padLeft:

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

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

After this, we define 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(":");
};

现在你可以像 Date <的任何其他方法一样使用此方法/ code> object:

Now you can simply use this method like any other method of the Date object:

var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());

但请记住,这种格式可能令人困惑。例如,当发行

But please bear in mind that this kind of formatting can be confusing. E.g., when issuing

new Date().toFormattedString()

该函数目前返回 07/06/10 22:05 。对我来说,这更像是6月7日而不是7月6日。

the function returns 07/06/10 22:05 at the moment. For me, this is more like June 7th than July 6th.

编辑:这只适用于年份可以使用四个 - 数字。在9999年12月31日之后,这将出现故障,您将不得不调整代码。

This only works if the year can be represented using a four-digit number. After December 31st, 9999, this will malfunction and you'll have to adjust the code.

这篇关于在JavaScript中将UNIX时间转换为mm / dd / yy hh:mm(24小时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆