skip to Main Content

When trying to make a date variable in JS and console.log(ing) it returns Invalid date, am I being stupid can someone help me.

let yr = String(new Date().getFullYear());
let mnth = new Date();
mnth = String(getMonthShortName(new Date().getMonth()));
let dte = String(new Date().getDate());
let hr = String(new Date().getHours());
let min = String(new Date().getMinutes());
let sec = String(new Date().getSeconds());
date2 = new Date(String(mnth + " " + dte + " " + yr + " " + hr + " " + min + " " + sec));
console.log("Date (full): " + date2);

function getMonthShortName(monthNo) {
  const date = new Date();
  date.setMonth(monthNo - 1);
  return date.toLocaleString('en-US', {
    month: 'short'
  });
}

2

Answers


  1. Chosen as BEST ANSWER

    Figured it out, just use: let date2 = new Date();


  2. Trying to understand what you wanted to do. If you just wanted to print the date in your format, then just remove the new Date() in date 2 and if you wanted a new date2 from the date1. then all of this was unnecessary.

    let yr = String(new Date().getFullYear());
    let mnth = new Date();
    mnth = String(getMonthShortName(new Date().getMonth()));
    let dte = String(new Date().getDate());
    let hr = String(new Date().getHours());
    let min = String(new Date().getMinutes());
    let sec = String(new Date().getSeconds());
    date2 = String(mnth + " " + dte + " " + yr + " " + hr + " " + min + " " + sec);
    console.log("Date (full): " + date2);
    
    function getMonthShortName(monthNo) {
      const date = new Date();
      date.setMonth(monthNo - 1);
      return date.toLocaleString('en-US', {
        month: 'short'
      });
    }

    if you trying to make a new date only

    // get the time value of the original date object
    const timeValue = date1.getTime();
    
    // create a new date object from the time value
    const date2 = new Date(timeValue);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search