stackato stackato - 6 months ago 11
Javascript Question

JavaScript -- slice time string to return HH:MM

I have a time/date string that is returned like so:

"5/31/2016, 2:23:33 PM"
. I need only the HH:MM and am/pm, so
2:23 PM


I am able to split the date off but not sure how I can remove the colon and seconds.

time = time.split(",")[0];
//time = " 2:23:33 PM";


thanks

Answer

Using a Date Object

While this is entirely feasible through a series of splits, regular expressions, etc, it may simply be easier to just use some of Javascript's built-in Date functionality (assuming that your format isn't going to vary wildly).

You could consider writing a function to parse your date as a Date object and then formatting it accordingly :

function formatDateStringAsTime(input){
  var date = new Date(input);
  // Determine if it is AM or PM
  var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
  // Output what you need
  return (date.getHours() % 12) + ':' + date.getMinutes() + ampm;
}

Additionally if you want to ensure you have two digits (i.e. zero padded values), you can use a bit of slicing to change that :

// Using this approach will pad your hours and minutes with zeros if necessary
return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;

Example

formatDateStringAsTime("5/31/2016, 2:23:33 PM"); // yields 2:23 PM 

var input = "5/31/2016, 2:03:33 PM";
input = formatDateStringAsTime(input);
console.log(input);

function formatDateStringAsTime(input) {
  var date = new Date(input);
  // Determine if it is AM or PM
  var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
  return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;
}

Consider Date-specific Libraries

As others have mentioned, if you are going to be performing this behavior frequently within your application, you might consider using a library like Date.js or Moment.js, which are designed for exactly this.

Comments