-4

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 .

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • You you want the date in a specific format. Why are you not using it in your string? – epascarello Jun 13 '23 at 14:14
  • You’re missing the day and the slashes. You get the month and add one to it; if you want to concatenate the string `”1”` you should do that. Or use a date formatter. Tangential: I wouldn’t create a new date every time you need a cake from a single date. – Dave Newton Jun 13 '23 at 14:14

1 Answers1

3

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);                            
};

// Convenience (parse and format)
const convertDate = (dateStr) => dateFormatter.format(parseDate(dateStr));

['6 2023', 'June 2023', 'foobar'].forEach((dateStr) => {
  try {
    console.log(convertDate(dateStr));
  } catch (e) {
    console.log(e.message);
  }
});

Vue example

Since you are using Vue, you can just define the function(s) outside of the Vue application and call the convertDate function when computing the model.

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);                            
};

const convertDate = (dateStr) => dateFormatter.format(parseDate(dateStr));

new Vue({
  el: '#app',
  data() {
    return {
      input: 'June 2023'
    }
  },
  computed: {
    output: function() {
      return convertDate(this.input);
    }
  }
});
html, body, #app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#app {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.25rem;
}

#app input {
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Date String Converter</h2>
  <input v-model="input">
  <p>{{ output }}</p>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • but you are hardcoding the values in array, i should be pass them as parameter to a function, and then i can use but how `['6 2023', 'June 2023', 'foobar']` – Smith Jonas Jun 13 '23 at 16:16
  • @SmithJonas I added a "convenience" function that parses and formats i.e. `convertDate`. See the updated code. Just call that function to do the conversion. The array or hardcoded data was just sample data for demonstration. – Mr. Polywhirl Jun 13 '23 at 16:20
  • @mr-polywhirl : i have to use it in vueJS so i tried like this – Smith Jonas Jun 13 '23 at 16:55
  • https://jsfiddle.net/vmhg327r/ , is that wrong or right – Smith Jonas Jun 13 '23 at 16:55
  • @SmithJonas what do you mean, "is that wrong or right"? That JS Fiddle code is busted. The code works fine in the snippet above. If you are using a framework like Vue, Angular, or React, you can just call the `convertDate` function as-is. Make the function globally accessible. – Mr. Polywhirl Jun 13 '23 at 17:21
  • i did called the Covertdate in another function, but all i get is undefined – Smith Jonas Jun 13 '23 at 17:32
  • please check, i created function out of your code and it seems directly const are used, and in convert, i see there are lot of other things used, it is as direct as i see – Smith Jonas Jun 13 '23 at 17:33
  • can't use this ins a function, why to use each here `const convertDate = (dateStr) => dateFormatter.format(parseDate(dateStr));` – Smith Jonas Jun 13 '23 at 17:33
  • see this fiddle https://jsfiddle.net/ezt83vo7/2/ – Smith Jonas Jun 13 '23 at 17:36
  • @SmithJonas I added a Vue example at the very bottom of the response. – Mr. Polywhirl Jun 13 '23 at 17:37
  • Thanks, but i think you are overcomplicating it for me, can we define it the way i showed you in fiddle, because that way i can define it in my methods, the example if complete i vue, but the structure is entirely different as to what we are using, Thanks for the efforts though – Smith Jonas Jun 13 '23 at 17:48
  • @SmithJonas you DO NOT want to redefine those functions inside of a Vue method. They will be redefined EVERY TIME you call said Vue function. Vue uses JavaScript, so just define all the formalities outside of a Vue component. PERIOD. You are complicating this by introducing Vue into the equation, Your original question never mentioned Vue. – Mr. Polywhirl Jun 13 '23 at 17:56
  • I fully understood but i do not have a choice to put those outside, so lets do it that way or we create a mixin, i can move those functions in mixins and that can sort things up, all i need is properly coded functions so i just call it and it returns me the date – Smith Jonas Jun 13 '23 at 18:17
  • no use of the code shared, its useless – Smith Jonas Jun 13 '23 at 19:04