简体   繁体   中英

Remove leading zeros from time format

I am receiving a string in this format 'HH:mm:ss' . I would like to remove the leading zeros but always keeping the the last four character eg m:ss even if m would be a zero. I am formatting audio duration.

Examples:

00:03:15 => 3:15
10:10:10 => 10:10:10
00:00:00 => 0:00
04:00:00 => 4:00:00
00:42:32 => 42:32
00:00:18 => 0:18
00:00:08 => 0:08

You can use this replacement:

var result = yourstr.replace(/^(?:00:)?0?/, '');

demo

or better:

var result = yourstr.replace(/^0(?:0:0?)?/, '');

demo


To deal with Matt example (see comments), you can change the pattern to:

^[0:]+(?=\d[\d:]{3})

Another option is to use moment.js libary.

This supports formats such as

var now = moment('1-1-1981 2:44:22').format('h:mm:ss');
alert(now);

http://jsfiddle.net/8yqxh5mo/

If you use 1 h instead of two you will not get the leading 0.

h:mm:ss

You could do something like this:

 var tc =['00:03:15', '10:10:10','00:00:00','04:00:00','00:42:32','00:00:18','00:00:08']; tc.forEach(function(t) { var y = t.split(":"); y[0] = y[0].replace(/^[0]+/g, ''); if(y[0] === '') { y[1] = y[1].replace(/^0/g, ''); } var r = y.filter(function(p) {return p!=='';}).join(':'); console.log(r); });

Divide the time in 3 parts. Remove the leading zeroes from first part, if the the first part is empty remove the leading zeroes from the second part otherwise keep it. Then join all of them discarding the empty strings.

I had a problem with ZUL time when simply format with one small 'h' moment(date).format('h:mm A') cuts first digit from time:

and my const arrivalTime = "2022-07-21T12:10:51Z"

const result = moment(arrivalTime).format(('h:mm A')) // 2:10 PM

Solution for that was converting that to ISO format and then format:

const arrivalTimeIsoFormat = arrivalTime.toISOString()
const result = moment(arrivalTimeIsoFormat, "YYYY-MM-DDTHH:mm:ss.SSS").format(('h:mm A')) // 12:10 PM

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