How to convert month year (YYYYmm) string to Datetime in Javascript?

Viewed 46

I have a Year and Month string "202008" which I need to convert into DateTime like 2020-08-01 00:00:00. What would be the best way to do it using Javascript or Momentjs?

2 Answers

Using plain JS

function toDate(str) {
  return str.replace(/(\d\d)(\d{4})/, "$2-$1-01 00:00:00");
}
console.log(toDate("082020"));

You can specify the input format in moment by using the second argument. moment(input, format)

moment('082020', 'MY').format('YYYY-MM-DD HH:mm:ss');
// 2020-08-01 00:00:00
Related