malimichael
malimichael

Reputation: 247

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

Upvotes: 13

Views: 15409

Answers (5)

Adriano
Adriano

Reputation: 924

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

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

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

Upvotes: 17

Gaurav Joshi
Gaurav Joshi

Reputation: 1001

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

h:mm:ss

Upvotes: 11

John
John

Reputation: 30586

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/

Upvotes: 3

abhishekkannojia
abhishekkannojia

Reputation: 2856

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.

Upvotes: 1

Related Questions