admin管理员组

文章数量:1312763

In javascript, I have a time string var time = "12:30:49PM"

I want to separate the hour, min, sec and AM/PM from that string.

Browsing stackoverflow I was able to find the following regex that split hour, min and Am/pm, but I am very bad at regex so I cant work out how to do the sec.

 var hours = Number(time.match(/^(\d+)/)[1]);
 var minutes = Number(time.match(/:(\d+)/)[1]);
 var AMPM = time.match(/([AaPp][Mm])$/)[1];

how to get the second via regex

In javascript, I have a time string var time = "12:30:49PM"

I want to separate the hour, min, sec and AM/PM from that string.

Browsing stackoverflow I was able to find the following regex that split hour, min and Am/pm, but I am very bad at regex so I cant work out how to do the sec.

 var hours = Number(time.match(/^(\d+)/)[1]);
 var minutes = Number(time.match(/:(\d+)/)[1]);
 var AMPM = time.match(/([AaPp][Mm])$/)[1];

how to get the second via regex

Share Improve this question asked Nov 4, 2016 at 20:16 codenoobcodenoob 5391 gold badge9 silver badges27 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 5

In your example, you would simply do something like:

var time = "12:30:49PM";   
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/([AaPp][Mm])$/)[1];
var seconds = Number(time.match(/:(\d+):(\d+)/)[2]);
console.log(hours, ":", minutes, ":", seconds, AMPM);  

However, it'd be more effecient to get everything in one call:

var time = "12:30:49AM";
var matches = time.match(/^(\d+):(\d+):(\d+)([AP]M)$/i);
var hours = matches[1];
var minutes = matches[2];
var seconds = matches[3];
var AMPM = matches[4];
console.log(hours, ":", minutes, ":", seconds, AMPM);

You can use a bination of regex with ES6 array destructuring:

const time = "12:30:49PM"
const [hour, min, sec, period] = time.match(/\d+|\w+/g);

console.log(hour, min, sec, period);

You can use it like so:

var time = "12:30:49PM"
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var sec = Number(time.match(/:(\d+)\D+$/)[1]);
var AMPM = time.match(/([ap]m)$/i)[1];
console.log(hours);
console.log(minutes);
console.log(sec);
console.log(AMPM);

Just split on colon and the (P\A)M part

var time  = "12:30:49PM";
var parts = time.split(/:|(\DM)/).filter(Boolean);

console.log(parts)

var sec = Number(time.match(/:([0-9][0-9])/ig)[1].replace(":",""))

How about!:

console.log(DateTimeFormat(new Date(), '`The Year is ${y} DateTime is: ${m}/${d}/${y} Time is: ${h}:${M}:${s}   `'))

function DateTimeFormat(dt, fmt)
{
    [y, m, d, h, M, s, ms] =  new 
    Date(dt).toLocaleString('UTC').match(/\d+/g)
    return eval(fmt)
}

本文标签: javascriptHow to Regex split time stringStack Overflow