Hmm... Can anyone help me a bit with this code?

function formatDate(d) {
  //if the date it's not the Object of Date, then exit.
  if (!date instanceof Date) {
    return;
  }
  var year = d.getFullYear(),
      month = d.getMonth() + 1, 
      date = d.getDate(), 
      hour = d.getHours(), 
      minute = d.getMinutes(), 
      second = d.getSeconds();
  month = month < 10 ? '0' + month : month;
  date = date < 10 ? '0' + date : date;
  hour = hour < 10 ? '0' + hour : hour;
  minute = minute < 10 ? '0' + minute:minute;
  second = second < 10 ? '0' + second:second;
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second

1.Like why should I judge the “date” instead of the “d”?
2. what should this paramater be when I run this code?
3. Error: d.getFullYear is not a function

  1. This is an error in your code, date is not a thing at that point, you’re using d everywhere else. date does get defined, but it’s the date part of the date object d, so it’ll always be a number.
  2. See 1
  3. d should be a Date object; if it isn’t a date object then this (and all other get functions) will fail.
function formatDate(d) {
  //if the date it's not the Object of Date, then exit.
  // if (!d instanceof Date) {
  //   console.log('if running')
  //   return;
  // }
  var year = d.getFullYear(),
      month = d.getMonth() + 1, 
      date = d.getDate(), 
      hour = d.getHours(), 
      minute = d.getMinutes(), 
      second = d.getSeconds();
  month = month < 10 ? '0' + month : month;
  date = date < 10 ? '0' + date : date;
  hour = hour < 10 ? '0' + hour : hour;
  minute = minute < 10 ? '0' + minute:minute;
  second = second < 10 ? '0' + second:second;
  console.log('formatDate running')
  var results =  year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
  console.log(results)
}
var testDate = new Date();
console.log(testDate)
formatDate(testDate);

I figure it out finnally! I think I didn’t really know the Date Object.
Thank u so much DanCouper!

1 Like