Search code examples
javascriptdatedayofweekquerystringparameter

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


I am facing some trouble while setting the right day of the week, I am using a query string parameter which is related to a calendar, and I want to use the selected date to another script which is fine, except that I can't set the right day. The query string parameter is in the following format: dd/mm/yyyy, and given this data I am trying to get the right day as well.

    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]);

Solution

  • You are treating methods of a date object as if they are data properties. You need to call them as methods, e.g.

    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()]);

    However, setting properties one at a time can introduce errors, e.g. if the month is created in April and you try to set the date for 31 May, when the date is set to 31 it will become 1 May (because there is no 31 April) so you'll end up with a date for 1 May not 31 May. So set all the values in one go:

    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());