最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert UNIX Time to mmddyy hh:mm (24 hour) in JavaScript - Stack Overflow

programmeradmin5浏览0评论

I have been using

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

And it will output for example:

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
//also 24 hour time

I have been using

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

And it will output for example:

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
//also 24 hour time

Share Improve this question asked Jul 6, 2010 at 15:36 Mark CheekMark Cheek 2652 gold badges10 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

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

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(":");
};

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()

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

EDIT: 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.

发布评论

评论列表(0)

  1. 暂无评论