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

How can I get the right day of the week, if I am setting the date in relation to the given query string parameters?

我在设置正确的星期几时遇到了一些问题,我正在使用与日历相关的查询字符串参数,我想将所选日期用于另一个脚本,这很好,除了我无法确定正确的日期。查询字符串参数采用以下格式: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());