Demo
https://jsfiddle.net/c59zsLux/1/
What I want to do
I want to erase the zero-filling from the millisecond section by moment.js.
Examples
0:00:00.000 → 0:0:0
0:16:55.404 → 0:16:55.404
1:00:30.100 → 1:0:30.1
1:09:01.770 → 1:9:1.77
Conditions
- The millisecond part has a maximum of three digits.
- I want to remove the trailing zeros from there.
- If all digits are zero, then it will not display the millisecond part.
My Implements
/**
* タイムスタンプを整形して返す
*
* @param {string|integer} ssms 秒(ss)とミリ秒(ms)で構成されたタイムスタンプ e.g. "4080.770" (01:08:00.770)
* @return {string} showTime e.g. "1:8:0.77"
*/
function formatTimestamp(time = 0)
{
if(time == 0){
return "0:0:0";
}
var ssms = time.split(".");
var temp_ss = ssms[0];
var temp_ms = ssms[1] ? ssms[1] : 0;
var m = moment.utc(temp_ss * 1000);
var hms = m.format("H:m:s");
var ms = removeTrailingZeros("." + temp_ms);
ms = ms ? ms : "";
var showTime = hms + ms;
return showTime;
}
/**
* 数字文字列の末尾のゼロを除去して返す
*
* [EXAMPLES]
* 1 -> 1
* 10 -> 10
* 100. -> 100
* 100.0 -> 100
* 100.1 -> 100.1
* 100.10 -> 100.1
* 100.01 -> 100.01
* 100.010 -> 100.01
* '1.2304000' -> 1.2304
* '1,000.000' -> 1,000
*
* @param {string|integer} value 数字文字列
* @return {string} value 末尾ゼロを除去した数字文字列
*/
function removeTrailingZeros(value)
{
var value = value.toString()
//console.log('Starting with:', value, value.indexOf('.'))
// ドット(ミリ秒)を含まない場合はそのままの値を返す
if (value.indexOf('.') === -1) {
return value;
}
var cutFrom = value.length - 1;
// ゼロの削除を末尾からドットの方向へ繰り返す
do {
//console.log('Checking:', value[cutFrom], cutFrom)
if (value[cutFrom] === '0') {
cutFrom--;
}
}
while (value[cutFrom] === '0');
// ドットの位置に来たら処理を終了する
if (value[cutFrom] === '.') {
cutFrom--;
}
return value.substr(0, cutFrom + 1);
}
I couldn't figure out how to do this in the moment.js options, so I implemented it from my own.
What I need from you all
If there is a smarter way to do this, or if it can be implemented with some option in moment.js, please let me know.
Thank you!