gpt4 book ai didi

javascript - 如果我根据给定的查询字符串参数设置日期,我怎样才能得到正确的星期几?

转载 作者:行者123 更新时间:2023-11-30 19:37:27 24 4
gpt4 key购买 nike

我在设置正确的星期几时遇到了一些麻烦,我正在使用与日历相关的查询字符串参数,我想将所选日期用于另一个脚本,这很好,除了我可以定好日子。查询字符串参数采用以下格式:dd/mm/yyyy,鉴于此数据,我也试图获得正确的日期。

    this.f = new Date();

this.f.setDate = getUrlParameter('date').split("/")[0];
this.f.setMonth = getUrlParameter('date').split("/")[1];
this.f.setFullYear = getUrlParameter('date').split("/")[2];
console.log(this.setMonth);

this.days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
this.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
console.log(this.months[this.setMonth]);

最佳答案

您将日期对象的方法视为数据属性。您需要将它们称为方法,例如

function getUrlParameter() {
return '12/04/2019';
}

// Replace this with plain obj
var obj = {};

obj.f = new Date();

// Call methods, don't assign to properties
// The set* methods set values
obj.f.setDate(getUrlParameter('date').split("/")[0]);

// Subtract 1 from calendar month number as EMCScript months are zero based, April is 3
obj.f.setMonth(getUrlParameter('date').split("/")[1] - 1);
obj.f.setFullYear(getUrlParameter('date').split("/")[2]);

// The get* methods get values
// Use getMonth to get the month
console.log(obj.f.getMonth());

obj.days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
obj.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

console.log(obj.months[obj.f.getMonth()]);

但是,一次设置一个属性可能会引入错误,例如如果该月份是在四月创建的,并且您尝试将日期设置为 5 月 31 日,则当日期设置为 31 时它将变为 5 月 1 日(因为没有 4 月 31 日),因此您最终会得到一个 5 月 1 日的日期不是 5 月 31 日。因此,一次性设置所有值:

let obj = {f: new Date()};
// Get date parta
let [day, month, year] = '31/05/2019'.split('/');

// Set values in one go
obj.f.setFullYear(year, month - 1, day);

console.log(obj.f.toLocaleDateString());

// But better to create the date with the right values
// from the start
let [day2, month2, year2] = '31/05/2019'.split('/');
let obj2 = {f: new Date(year2, month2 - 1, day2)};

console.log(obj2.f.toLocaleDateString());

关于javascript - 如果我根据给定的查询字符串参数设置日期,我怎样才能得到正确的星期几?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55788039/

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