skip to Main Content

I have a date:

 console.log(lastDayDate)

Output:

Sun Apr 30 2023 00:00:00 GMT-0500 (Central Daylight Time)

Then I use:

formattedDate = lastDayDate.toLocaleString().split(',')[0];
console.log(formattedDate)

Output is:

 4/30/2023

How can I change it to :

04/30/2023

4

Answers


  1. you could fix it with
    `let lastDayDate = new Date("Sun Apr 30 2023 00:00:00 GMT-0500 (Central Daylight Time)");

    let day = String(lastDayDate.getDate()).padStart(2, ‘0’);
    let month = String(lastDayDate.getMonth() + 1).padStart(2, ‘0’); // Se suma 1 porque getMonth() devuelve el mes de 0 (enero) a 11 (diciembre)
    let year = lastDayDate.getFullYear();

    let formattedDate = ${month}/${day}/${year};

    console.log(formattedDate); // Debería imprimir: 04/30/2023`

    Login or Signup to reply.
  2. You can split the 4/30/2023 bit with / and check whether the date/month is less than 10. Created a function for that (also checks the date):

    let formattedDate = "4/30/2023";
    
    function addZero(originalDate){
      date = originalDate.split("/");
      for (let i = 0; i < 2; i++){
        if (+date[i] < 10){ // Shorthand of parseInt
          date[i] = "0" + date[i];
        }
      }
      return date.join("/");
    }
    console.log(addZero(formattedDate));

    🙂

    Login or Signup to reply.
  3. You can use Date#toLocaleDateString with additional options.

    console.log(new Date().toLocaleDateString('en-US', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    }));
    Login or Signup to reply.
  4. Since you are using JavaScript, there are a lot of awesome 3’rd party libraries out there that can help you play around date object. The most advisable 2 are momentjs and date-fns.

    Creating a moment instance of a js Date() object is quite easy,

    import moment from 'moment';
    const timestamp = new Date();
    const momentTimestamp = moment(timestamp);
    
    momentTimestamp.format('MM/DD/YYYY')
    
    

    moment.js also has a crazy amount of formats available, for all other requirements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search