我想知道是否可以将 e.data.date
自定义为更适合我的需求的字符串输出。例如,目前,e.data.date
将输出为 Thu Jun 2012 2014 2000:00:00 GMT+0100 (BST)
但理想情况下我想复制 20140607
的事件开始和结束日期输入。
e.data.date
是 date object .
我可以使用 e.data.date.getUTCDate()
来获取月份,例如,但要获取所需的输出 20141102
,例如,其中包括年月日,好像没有getter方法...
有什么想法吗?
最佳答案
Date.prototype.GetCustomFormat = function ()
{
return this.getFullYear()+""+getInTwoDigitFormat(Number(this.getMonth())+1)+""+getInTwoDigitFormat(Number(this.getDay())-1);
};
function getInTwoDigitFormat(val)
{
return val < 10 ? '0' + val : val;
}
你可以这样调用它 new Date().GetCustomFormat();
2014 年 9 月 24 日更新:
Date.prototype.format = function (format)
{
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
return format;
};
通过这种方式,您可以比实现自定义库更快地格式化任何日期。 例如:
x=new Date();
Date {Wed Sep 24 2014 14:30:22 GMT+0300 (GTB Standard Time)}
x.format('M')
"9"
x.format('d')
"24"
x.format('d M')
"24 9"
x.format('d:M')
"24:9"
x.format('d:MM')
"24:09"
x.format('d:MM:yy')
"24:09:14"
x.format('d:MM:yyy')
"24:09:014"
关于javascript - 自定义 JS 数据对象以适应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322852/