0

I have some data that's inconsistent. It's all time related but I have some records that shows 3pm others 14:00.

Is there an easy way to normalize that in JS?

Thanks

MrRobot
  • 1,001
  • 1
  • 14
  • 34
  • Is it only the hours:minutes, or dates involved as well? – Aydin4ik Jan 21 '20 at 01:25
  • Only hours:minutes. – MrRobot Jan 21 '20 at 01:26
  • I'd recommend looking at https://www.w3schools.com/js/js_date_formats.asp One of my favorite methods is to convert times/dates into milliseconds since January 1, 1970 via "getTime()". Then you can compare and dates including the difference between them. – JLowther Jan 21 '20 at 01:27
  • You could write a function that converts time in this format *3pm*, *3:30pm* to the *military time*. – GetSet Jan 21 '20 at 01:27
  • https://momentjs.com/ – Bryan Dellinger Jan 21 '20 at 01:27
  • How are you going to use those times? If times of different dates are going to interact somehow, you will need to store dates as well. If you are only comparing times of the same date/calculating time passed, then convert to Epoch. – Aydin4ik Jan 21 '20 at 01:30
  • @Aydin4ik it could be times for when to order a burger for all we know – GetSet Jan 21 '20 at 01:31
  • It's basically the time that the store is open – MrRobot Jan 21 '20 at 01:34
  • https://stackoverflow.com/questions/4898574/converting-24-hour-time-to-12-hour-time-w-am-pm-using-javascript – Aydin4ik Jan 21 '20 at 01:38

1 Answers1

1

This function will return you a 24-hour-formatted time

function normaliseTime(time) {
    // If there is AM/PM in the string, do conversion
    if (time.toUpperCase().indexOf('M') >= 0) {
      // Remove the AM/PM text and split the hour and minute
      var tmArray = time.replace(/\D/g, '').split(':');
      // If PM, add 12 to the hour
      if (time.toUpperCase().indexOf('PM') >= 0) {
        tmArray[0] = parseInt(tmArray[0]) + 12;
      }
      // If minutes were not provided (i.e., 3PM), add 00 as minutes
      if (tmArray.length < 2) {
        tmArray[1] = '00';
      }
      return tmArray.join(':');
    }
    // If there was no AM/PM in the input, return it as is
    return time;
}
Aydin4ik
  • 1,782
  • 1
  • 14
  • 19