Convert PHP MySql format date in JavaScript Date

In most of the places in UI you need to display date and time in your format weather API is providing date and time in MySql Format that is YYYY-MM-DD H:M. To convert this I have created a function that can be used easily in javascript without and dependency.

function formatDateMysql(mysqldate) {
  let dateTimeParts= mysqldate.split(/[- :]/); // regular expression split that creates array with: year, month, day, hour, minutes, seconds values
  dateTimeParts[1]--; // monthIndex begins with 0 for January and ends with 11 for December so we need to decrement by one
  const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

  const d = new Date(...dateTimeParts); // our Date object
  var dd   = d.getDate();
  var hour = d.getHours();
  var minu = d.getMinutes();

  if(dd<10)  { dd='0'+dd }
  if(minu<10){ minu='0'+minu } 

  var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
  var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
  return monthNames[d.getUTCMonth()].toUpperCase()+" "+dd+", "+d.getUTCFullYear()+" "+hour+":"+minu +" "+amOrPm;
}

 

Call for test:

let a = formatDateMysql("2019-01-15 20:50:12");
console.log(a);

Output:

JANUARY 15, 2019 8:50 PM

Keywords: