简体   繁体   中英

How to Regex split time string

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

You can use a combination 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); 

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 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM