2014-07-03 62 views
0

我正在使用日历插件,并且该插件有几个回调事件,允许您自定义用户单击日期时发生的情况等。设置此的一种方法是对我而言,如下:Javascript日期对象和Date.prototype自定义

onDayClick: function(e) { 
    window.location.href = 'http://www.testdomain.com/events/day/' + e.data.date; 
} 

.datedate object如此,如果点击,例如,将返回:

http://www.testdomain.com/events/day/Thu Jun 2012 2014 2000:00:00 GMT+0100 (BST)

我需要的是期望的输出:

http://www.testdomain.com/events/day/2014/07/17/并查看了日期对象文档,我认为这相当简单。

Date.prototype.GetCustomFormat = function() { 
    return this.getFullYear()+'/'+getInTwoDigitFormat(this.getMonth())+'/'+getInTwoDigitFormat(this.getDate()); 
}; 
function getInTwoDigitFormat(val) { 
    return val < 10 ? '0' + val : val; 
} 

onDayClick: function(e) { 
    window.location.href = 'http://www.testdomain.com/events/day/' + e.data.date.GetCustomFormat(); 
} 

但是,这是什么带来回来,当点击,是正确的一年......但错误的月份1和错误的日期几天。奇怪的。所以我增加了一些门店并增加了一个UTC月...

return this.getFullYear()+'/'+getInTwoDigitFormat(this.getUTCMonth()+1)+'/'+getInTwoDigitFormat(this.getDate()); 

这似乎现在工作。但是,如果我有一次登陆的事件...它使用前一个月的第一个事件。所以,如果我点击7月1日,它将返回6月1日。

我想我正在抓住它......但这里和那里有一些奇怪的结果。任何人都可以发现我出错的地方,并让我正确吗?

感谢

+0

奇怪的部分是它也带来了错误的一天。预计该月为-1,因为其零指数。 – DontVoteMeDown

+0

因为这是UTC月份,假设你在7月1日_MMT + 0100_ _midnight_,那么UTC月份会少一点是不正常的呢? –

回答

1

这个解释很简单:因为你是1小时比UTC的,在午夜在7月1日,UTC仍然在六月!这就是为什么它使用UTC月份输出6月1日。使用UTC月份而不是UTC年份和日期没有太大意义,所以相反,只需使用常规月份:

Date.prototype.GetCustomFormat = function() { 
    return this.getFullYear()+'/'+getInTwoDigitFormat(this.getMonth()+1)+'/'+getInTwoDigitFormat(this.getDate()); 
}; 
var testerDate = new Date(Date.parse("Thu Jun 1 2012 00:00:00 GMT+0100")) 
testerDate.GetCustomFormat() //The output of this depends on your time zone: It'll be 2012/06/01 if in or ahead of GMT+0100, but otherwise, it'll be 2012/05/31. 
+0

你知道......我确信我原来是这样的,但没有奏效。但唉,它有:)谢谢你的重申。 –