简体   繁体   中英

How do you calaculate today's date with JavaScript for VueJS?

I'm building an app on the MEVN stack.

I'm fixing some bugs before an MVP I'm on track to release by the end of the month. This module to handle dates has me a bit flustered.

This function seems to be returning the date but 1 month behind. I'm trying to figure out why that is happening.

This JS module needs to return a few formats: mm/dd/yyyy mm/dd/yyyy AT "hh:mm am/pm" yyyy-mm-dd

This is the function that's returning the wrong month

function getCurrentDateAndTime() {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth();
  var date = d.getDate();
  var hours = d.getHours();

  function checkMinutes(mins) {
    if (mins.length < 2) {
      return "0" + mins;
    } else {
      return mins;
    }
  }
  var minutes = checkMinutes(d.getMinutes());
  var monthDateYear = `${month}/${date}/${year}`;

  getHours = (hours) => {
    if (hours >= 13 && hours < 25) {
      return hours - 12;
    } else if (hours == 0) {
      return "12";
    } else if (hours == 12) {
      return "12";
    } else {
      return hours;
    }
  };

  amPm = (hours) => {
    if (hours < 13) {
      return "AM";
    } else {
      return "PM";
    }
  };

  var amOrPm = amPm(hours);
  time = `${getHours(hours)}:${minutes}`;
  timeAmPm = `${time} ${amOrPm}`;

  var dateAndTime = `${monthDateYear} AT ${time} ${amOrPm}`;
  var currentDateAndTime = {
    date: monthDateYear,
    time: timeAmPm,
    dateAndTime: dateAndTime
  };
  return currentDateAndTime;
}

I haven't noticed an issue with this code (yet) but I'm also cleaning up loads of spagetti code at the moment so I'm not even sure if it's in use yet HOWEVER, I think I used the same general code with a different format.

function getCurDateSQL() {
  var date = new Date(new Date()).toDateString();
  var d = new Date(date),
    month = "" + (d.getMonth() + 1),
    day = "" + d.getDate(),
    year = d.getFullYear();
  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;
  return [year, month, day].join("-").toString();
}

If I have a bug in my code, I'm failing to see it and I have tunnel vision at this point.

The month is indexed at 0 with the Date() function so you need to add 1 to the month

mm/dd/yyyy:

date = `${month +1}/${day}/${year}`

and yyyy-mm-dd:

sqlDate = `${year}${month +1}-${day}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM