0
(function () {
    var date = new Date().toISOString().substring(0, 10),
        field = document.querySelector('#date');
    var day = new Date(date);
    var getMonday = day.getDay(),
        diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
    field.value = new Date(date.setDate(diff));
    console.log(date);
})();

I am trying to get the Monday of the current date.

I keep getting errors about it and not sure how to resolve it

TypeError: date.getDate is not a function
    at index.html:394
    at index.html:398
(anonymous) @ index.html:394
(anonymous) @ index.html:398

Post of so called Duplicate only asks for the how to get the date. My question has similar code but I am getting error messages that was never addressed in the question

software is fun
  • 7,286
  • 18
  • 71
  • 129
  • 2
    Possible duplicate of [JavaScript - get the first day of the week from current date](http://stackoverflow.com/questions/4156434/javascript-get-the-first-day-of-the-week-from-current-date) – GillesC Feb 10 '17 at 23:26
  • @GillesC I have new information in my posting that is not answered by the question – software is fun Feb 10 '17 at 23:28
  • You are trying to get **getDate()** from string - it doesn't have such method, use **date** type instead – Alexey Feb 10 '17 at 23:30

1 Answers1

2

You transform the date to string in the first line: date = new Date().toISOString().substring(0, 10) that is what causes the error... date is no longer a Date object.

--- EDIT: Solution I would suggest you to either declare an additional variable for any of your later use as ISO string, or to make the conversion after only when output: For this, I'd suggest add your format to the Date object's prototype

Date.prototype.myFormat = function() { 
    return this.toISOString().substring(0, 10); 
}

Update your initial code like this:

var date = new Date(), 
str_date=date.toISOString().substring(0, 10),
field = document.querySelector('#date'), 
day = new Date(date),
getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);

console.log(date);
console.log(str_date);
console.log(new Date(date.setDate(diff)));
console.log(new Date(date.setDate(diff)).myFormat());

//Now you can update your field as needed with date or string value
field.value = new Date(date.setDate(diff));
field.value = new Date(date.setDate(diff)).myFormat();

If you need it in more places make the getMonday also a function...

Happy coding, Codrut

Codrut TG
  • 668
  • 7
  • 10