gpt4 book ai didi

Javascript 日期对象和 Date.prototype 定制

转载 作者:行者123 更新时间:2023-12-03 12:18:30 24 4
gpt4 key购买 nike

我正在使用日历插件,该插件有一些回调事件,允许您自定义用户单击日期等时发生的情况。对我来说,设置此功能的一种方法如下:

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 和错误的日期几天。诡异的。所以我添加了一些偏移量并添加了 UTCMonth...

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

这似乎现在有效。但是,如果我有一个事件在 1 号举行……它会使用上个月的 1 号。因此,如果我点击 7 月 1 日,它将返回 6 月 1 日。

我想我已经明白了...但是到处都有一些奇怪的结果。谁能发现我哪里出了问题并纠正我?

谢谢

最佳答案

对此的解释很简单:因为您比 UTC 早一小时,所以在 7 月 1 日午夜,UTC 仍然是 6 月!这就是为什么它使用 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.

关于Javascript 日期对象和 Date.prototype 定制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24555538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com