Reputation: 2615
I am using a calendar plugin, and the plugin has a few callback events allowing you to customise what happens when a user clicks a date etc. One way to set this is up, for me, is the following:
onDayClick: function(e) {
window.location.href = 'http://www.testdomain.com/events/day/' + e.data.date;
}
.date
is a date object so, if clicked, for example, this would return:
http://www.testdomain.com/events/day/Thu Jun 2012 2014 2000:00:00 GMT+0100 (BST)
What I need is the desired output of:
http://www.testdomain.com/events/day/2014/07/17/
and having a look at the date object documentation, I thought this would be fairly easy.
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();
}
But, what this brings back, when clicked, is the right year... but the wrong month by 1 and the wrong date by a few days. Weird. So I added some offets and added a UTCMonth...
return this.getFullYear()+'/'+getInTwoDigitFormat(this.getUTCMonth()+1)+'/'+getInTwoDigitFormat(this.getDate());
This seems to work now. However, if I have an event that lands on the 1st... it uses the 1st from the previous month. So, if I click on 1st July, it returns 1st June.
I think I'm grasping it... but there's a few odd results here and there. Can anyone spot where I am going wrong and put me right?
Thanks
Upvotes: 0
Views: 89
Reputation: 1784
This explanation to this is simple: Because you're one hour ahead of UTC, at midnight on the first of July, UTC is still in June! That's why it outputs June 1st from using the UTC month. Using the UTC month and not UTC year and date doesn't make much sense, so instead, just use the regular month:
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.
Upvotes: 1