简体   繁体   English

从时间格式中删除前导零

[英]Remove leading zeros from time format

I am receiving a string in this format 'HH:mm:ss' .我收到格式为'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.我想删除前导零,但始终保留最后四个字符,例如m:ss即使m为零。 I am formatting audio duration.我正在格式化音频持续时间。

Examples:例子:

00:03:15 => 3:15 00:03:15 => 3:15
10:10:10 => 10:10:10 10:10:10 => 10:10:10
00:00:00 => 0:00 00:00:00 => 0:00
04:00:00 => 4:00:00 04:00:00 => 4:00:00
00:42:32 => 42:32 00:42:32 => 42:32
00:00:18 => 0:18 00:00:18 => 0:18
00:00:08 => 0:08 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:要处理 Matt 示例(请参阅评论),您可以将模式更改为:

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

Another option is to use moment.js libary.另一种选择是使用 moment.js 库。

This supports formats such as这支持格式,例如

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

http://jsfiddle.net/8yqxh5mo/ http://jsfiddle.net/8yqxh5mo/

If you use 1 h instead of two you will not get the leading 0.如果您使用 1 h 而不是 2,您将不会获得前导 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.将时间分成 3 部分。 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:当简单地用一个小的 'h' moment(date).format('h:mm A')从 time 中删除第一个数字时,我遇到了 ZUL time 的问题:

and my const arrivalTime = "2022-07-21T12:10:51Z"我的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:解决方案是将其转换为 ISO 格式,然后格式化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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