Convert a string in date (so formatted: month day, year hh:mm:ss)

759 Views Asked by At

I know there are tons of questions about date formatting, but I'm stuck with a conversion.
I have a string so formatted: mag 11, 2021 2:31:00 pm ("mag" is the abbreviation of May in italian).
I want to convert it in date so I can change it to the format DD/MM/YYYY HH:MM:ss (in this case "11/05/2021 14:31").
I tried to use the new Date or Date.parse functions, but in console it returns me the error 'Invalid date'.
Here's what I tried:

let a = "mag 11, 2021 2:31:00 pm";
let b = new Date(a);
console.log(b);
console output -----> Invalid Date

let a = "mag 11, 2021 2:31:00 pm";
let b = Date.parse(a);
console.log(b);
console output -----> NaN

Any idea? Thx

2

There are 2 best solutions below

0
On
let now = new Date();

var dateString = moment(now).format('YYYY-MM-DD');
console.log(dateString) // Output: 2020-07-21

var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:MM:SS');
console.log(dateStringWithTime) // Output: 2020-07-21 07:24:06

You can check here for all details of dateTime for Javascript

0
On

This question has been answered many times before, the following is for this specific case.

A Date object isn't required, the timestamp can be split into its parts, the month name converted to a number then the parts reformatted, e.g.

/*
mag 11, 2021 2:31:00 pm => DD/MM/YYYY HH:MM:ss 
e.g. 11/05/2021 14:31
*/
function reformatDate(date) {
  let z = n => ('0'+n).slice(-2);
  let months = [,'gen','feb','mar','apr','mag','giu',
                 'lug','ago','set','ott','nov','dic'];
  let [M,D,Y,h,m,s,ap] = date.toLowerCase().split(/\W+/);
  h = h%12 + (ap == 'am'? 0 : 12);
  M = months.indexOf(M);
  return `${z(D)}/${z(M)}/${Y} ${z(h)}:${m}`;
}

console.log(reformatDate('mag 11, 2021 2:31:00 pm'));

In the OP, the format tokens include seconds but the example doesn't. Adding seconds to the above output if required should be easy.

The above can be modified to build the month names array based on a specific language, but then language to use would need to be passed to the function too.

If a library is used to parse the string, the language and format must be specified for the parser (e.g. date-fns allows setting the parse and format language), then the language and format of the output. So unless other date manipulation is required, a library may be more trouble than it's worth.