Remove leading zeroes in datestring

2020-04-27 04:27发布

I have a date string like the following: 2011-02-03. I want to remove the leading zeroes in the day and month part of the string. How do I do this?

标签: javascript
4条回答
劳资没心,怎么记你
2楼-- · 2020-04-27 04:31

Without regex:

function stripLeadingZerosDate(dateStr){
    return dateStr.split('-').reduce(function(date, datePart){
        return date += parseInt(datePart) + '-'
    }, '').slice(0, -1);
}

stripLeadingZerosDate('01-02-2016')      // 1-2-2016
stripLeadingZerosDate('2016-02-01')      // 2016-2-1
查看更多
你好瞎i
3楼-- · 2020-04-27 04:41

The naive way to do this is to split the string on -, then if the value at index 1 or 2 starts with a 0, replaceAll 0 with ''. Something like (I didn't test this)

var tokens = '2011-02-03'.split('-'),
    mm = tokens[1],
    dd = tokens[2];

if (mm.charAt(0) === '0') tokens[1] = mm.replace("0", "");
if (dd.charAt(0) === '0') tokens[2] = dd.replace("0", "");

var newString = tokens[0] + "-" tokens[1] + "-" + tokens[2];
查看更多
▲ chillily
4楼-- · 2020-04-27 04:53
"2011-02-03".replace(/-0+/g, '-'); // => "2011-2-3"

[Update]

Per @Lucky's question, you can account for other formats that might have a leading zero as such:

"02-03".replace(/(^|-)0+/g, "$1"); // => "2-3"
查看更多
beautiful°
5楼-- · 2020-04-27 04:53

You can use the library http://www.datejs.com/ which give you a lot of formatting option if you do not want to use the substring method.

查看更多
登录 后发表回答