skip to Main Content

I have this kind of code where I only get month and year

dates are coming as : "6 2023"

let checkCurrentDate = new Date().getMonth() + 1 + ' ' + new Date().getFullYear();
console.log(checkCurrentDate);

I want the date to be in mm/dd/yyyy format. Also, in some cases, dates are coming as "June 2023" and I need the date in the same mm/dd/yyyy format. Please guide what I am missing here .

The dd should be the first of every month .

2

Answers


  1. There are two ways to format a date a string in English US format.

    1. Using a reusable formatter instance Intl.DateTimeFormat
    2. Calling toLocaleDateString
    const dateFormatter = new Intl.DateTimeFormat('en-US');
    
    // Reusable formatter
    console.log(dateFormatter.format(new Date()));
    
    // Inline locale string
    console.log(new Date().toLocaleDateString('en-US'));

    If you want padding, you need to specify 2-digit as an option for month and day.

    Note: Don’t forget the year!

    const dateFormatter = new Intl.DateTimeFormat('en-US', {
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    });
    
    // Reusable formatter
    console.log(dateFormatter.format(new Date()));
    
    // Inline locale string
    console.log(new Date().toLocaleDateString('en-US', {
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    }));

    Now, to put it all together:

    const dateFormatter = new Intl.DateTimeFormat('en-US', {
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    });
    
    const parseDate = (dateStr) => {
      const tokens = dateStr.split(/s/g); // <MONTH_INDEX|MONTH_NAME> <YEAR>
      if (tokens.length !== 2) throw new Error(`Illegal date format: ${dateStr}`)
      return !isNaN(dateStr[1])
        ? new Date(+tokens[1], +tokens[0] - 1, 1)               // Numeric month
        : new Date(Date.parse(`${tokens[0]} 1, ${tokens[1]}`)); // Month name
    };
    
    ['6 2023', 'June 2023', 'foobar'].forEach((dateStr) => {
      try {
        console.log(dateFormatter.format(parseDate(dateStr)));
      } catch (e) {
        console.log(e.message);
      }
    });

    Output

    06/01/2023
    06/01/2023
    

    Here is a better version that is more efficient at parsing the month name. All the months for the en-US are generated ahead of time.

    const getLocalMonthNames = (locale = 'default', format = 'long') =>
      Array.from({ length: 12 }, (_, monthIndex) =>
        new Date(0, monthIndex, 1).toLocaleString(locale, { month: format }));
    
    const monthNames = getLocalMonthNames('en-US');
    const dateFormatter = new Intl.DateTimeFormat('en-US', {
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    });
    
    const parseDate = (dateStr) => {
      const tokens = dateStr.split(/s/g); // <MONTH_INDEX|MONTH_NAME> <YEAR>
      if (tokens.length !== 2) throw new Error(`Illegal date format: ${dateStr}`);
      const monthIndex = !isNaN(dateStr[1])
        ? +tokens[0] - 1                   // Numeric month
        : monthNames.indexOf(tokens[0]);   // Month name
      return new Date(+tokens[1], monthIndex, 1);                            
    };
    
    ['6 2023', 'June 2023', 'foobar'].forEach((dateStr) => {
      try {
        console.log(dateFormatter.format(parseDate(dateStr)));
      } catch (e) {
        console.log(e.message);
      }
    });
    Login or Signup to reply.
  2. I’d suggest checking the documentation first before asking a question here.
    I understand that working with dates might be tricky, but all your answers could be found here

    Alternatively, you could use packages like moment or dayjs

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