3

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);
Akshay Chawla
  • 613
  • 1
  • 8
  • 16
Bruno
  • 511
  • 2
  • 6
  • 19
  • Did you try using [`moment.js`](http://momentjs.com/) or is that not an option? – ssc-hrep3 May 23 '17 at 10:59
  • 1
    I am using phonegap with the intention of making this an app, so if possible I would like to avoid external libraries. – Bruno May 23 '17 at 11:00
  • The return value of `setDate()` is not a Date, so you need to split this line: `var priordate = new Date().setDate(beforedate.getDate()-30);` – ssc-hrep3 May 23 '17 at 11:03

3 Answers3

6

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.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
3

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

marvinhagemeister
  • 2,801
  • 1
  • 22
  • 27
  • I was under the impression that only using javascript was possible when developing with cordova/phonegap. I'll definitely check that video and might consider using moment.js. Thanks for your input! – Bruno May 23 '17 at 11:06
1

Change this:

var priordate = new Date().setDate(beforedate.getDate()-30);

to this:

var priordate = new Date();
priordate.setDate(beforedate.getDate()-30);
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63