gmc1972 gmc1972 - 1 year ago 88
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';
var res = formatTime(time);

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];

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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download