Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getmonth() is not a function error parsing date

Tags:

javascript

I have an object with a production_date which I'm trying to extract year and month but I keep getting getMonth() and getYear() is not a function error...

function(d) { 
          var dt = d.production_date
          var dtm = dt.getMonth();
          var dty = dt.getYear();
          return dtm + "/" + dty 
       }
like image 367
lightweight Avatar asked Nov 22 '16 20:11

lightweight


2 Answers

function(d) { 
          var dt = new Date(d.production_date);
          var dtm = dt.getMonth();
          var dty = dt.getFullYear();
          return dtm + "/" + dty 
       }

If it's passed over network, you'll only have a number (timestamp)

like image 180
gr3g Avatar answered Nov 09 '22 00:11

gr3g


Make sure that is a valid date. If it is a string ,you can convert it into date using new Date("datestring"),make sure that datestring is in the following format "YYYY/MM/DD" ,if so you can do it as the following

var d = {
  "production_date": "2016/11/23"
}
var val = getMonthYear(d);
console.log(val);

function getMonthYear(d) {
  var dt = new Date(d.production_date);
  var dtm = dt.getMonth();
  var dty = dt.getYear();
  return dtm + "/" + dty
}

Hope it helps

like image 1
Geeky Avatar answered Nov 08 '22 23:11

Geeky