admin管理员组

文章数量:1318564

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

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

Share Improve this question asked May 31, 2016 at 18:31 stackatostackato 1,1451 gold badge20 silver badges39 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4

If starting with a date/time string and desiring to end with a time string, of the same format, consider the following regular expression with two capture groups:

var dateStr = "5/31/2016, 2:23:33 pm";
var m = dateStr.match(/(\d{1,2}:\d{2}):\d{2}\s+?(AM|PM)/i)
//                      ^-- 1                    ^-- 2
if (m) {
   console.log(m[1] + " " + m[2].toUpperCase()); // "2:23 PM"
}

Otherwise, if ever needing to deal with a proper date/time object I'd consider moment.js - and specify the appropriate conversion format.

I would not use new Date(nonISO8601String) for parsing as it is unreliable across browsers/localizations.

I suggest using moment.js to parse the string and then output as a formatted string like this

var input = "5/31/2016, 2:23:33 PM";
var result = moment(input);

console.log(result.format("hh:mm a"));
//output: 02:23 pm

Fiddle

Update

As others have mentioned, although this answer does work as expected, that may not be the case across all browsers and locales the same.

My remendation would preferably to use one of the popular date libraries like Moment.js, which could be argued as the de facto standard at the present time for handling this.

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.

You can do it in two lines using this regex:

var a = new Date("5/31/2016, 2:23:33 PM");

var b = a.toLocaleTimeString().replace(/:\d{2}\s/,' ');
console.log(b)

Parsing of strings using the Date constructor (and Date.parse) is largely implementation dependent and inconsistent across browsers so should not be relied upon. If parsing is required, use a bespoke function or library, there are plenty to choose from.

But reformatting a string doesn't require parsing, just extracting the required values. There are any number of simple ways to manipulate the string, here are two (note that leading zeros for hours are typically only used for 24 hour time formats):

// Extract h:mm ap ponent of a string in m/d/y h:mm:ss ap format
function getTime(s) {
  var b = s.split(/\D/);
  function z(n){return (n<10?'0':'')+n}
  return z(b[4]) + ':' + z(b[5]) + ' ' + s.slice(-2);
}

document.write(getTime('5/31/2016, 2:23:33 PM'));

And (though this doesn't add leading zeros):

document.write(
  '5/31/2016, 2:23:33 PM'.replace(/[^\s]*,\s|:\d+\s/g,' ').trim()
);

本文标签: dateJavaScriptslice time string to return HHMMStack Overflow