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?
CodePudding user response:
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
CodePudding user response:
Using plain JS
function toDate(str) {
const d = new Date(str.replace(/(\d\d)(\d{4})/, "$2-$1-01T00:00:00"));
// en-ca because Canadians do dates like yyyy-mm-dd
return new Intl.DateTimeFormat('en-CA', {
dateStyle: "short",
timeStyle: 'medium',
hour12:false,
hourCycle: 'h23',
}).format(d).replace(',', '');
}
console.log(toDate("082020"));