gmc1972 gmc1972 - 4 months ago 12
Javascript Question

Javascript number like time regex format

I'm receiving from my database time like hh:mm:ss, and in javascript i would like to put the time like hh:mm
this is my code



var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);

function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
}





The function doesn't work well since i receive "false", any help?

Thanks

Answer

May be I am missing something in the question, but if you simply want to extract the hh:mm part from hh:mm:ss, then this should work:

// var time = "hh:mm:ss";
var time = "10:01:30";
var splitTime = time.trim().split(":"); // trim to remove any leading and trailing spaces
var formattedTime = splitTime[0] +":"+ splitTime[1];
console.log( formattedTime );