I am trying to populate two date input fields, one with today's date and one with the date 30 days ago(last month).
I am getting an error in my console: priordate.getDate is not a function
Here is my code, not sure what I am doing wrong:
//today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;
//30 days ago
var beforedate = new Date();
var priordate = new Date().setDate(beforedate.getDate()-30);
var dd2 = priordate.getDate();
var mm2 = priordate.getMonth()+1;//January is 0, so always add + 1
var yyyy2 = priordate.getFullYear();
if(dd2<10){dd2='0'+dd2};
if(mm2<10){mm2='0'+mm2};
var datefrommonthago = yyyy2+'-'+mm2+'-'+dd2;
// Set inputs with the date variables:
$("#fromdate").val(datefrommonthago);
$("#todate").val(today);
You'll instead want to use:
var priordate = new Date(new Date().setDate(beforedate.getDate()-30));
if you want it on one line. By using:
new Date().setDate(beforedate.getDate()-30);
you're returning the time since epoch (a number, not a date) and assigning it to priordate, but it's not a Date anymore and so does not have the getDate function.
This is because setDate() returns a number, not a Date Object.
In any I case I'd strongly recommend using momentjs or date-fns as the internal Date object in JavaScript is broken in all kind of ways. See this talk: https://www.youtube.com/watch?v=aVuor-VAWTI
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With