How do I use .toLocaleTimeString() without displaying seconds?

前端 未结 11 969
小蘑菇
小蘑菇 2020-12-07 15:56

I\'m currently attempting to display the user\'s time without displaying the seconds. Is there a way I can do this using Javascript\'s .toLocaleTimeString()?

Doing s

11条回答
  •  一生所求
    2020-12-07 16:36

    I've also been looking for solution to this problem, here's what I eventually came up with:

    function getTimeStr() {
        var dt = new Date();
        var d = dt.toLocaleDateString();
        var t = dt.toLocaleTimeString();
        t = t.replace(/\u200E/g, '');
        t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, '$1$2');
        var result = d + ' ' + t;
        return result;
    }
    

    You can try it here: http://jsfiddle.net/B5Zrx/

    \u200E is some formatting character that I've seen on some IE version (it's unicode left-to-right mark).

    I assume that if the formatted time contains something like "XX:XX:XX" then it must be time with seconds and I remove the last part, if I don't find this pattern, nothing is changed. Pretty safe, but there is a risk of leaving seconds in some weird circumstances.

    I just hope that there is no locale that would change the order of formatted time parts (e.g. make it ss:mm:hh). This left-to-right mark is making me a bit nervous about that though, that is why I don't remove the right-to-left mark (\u202E) - I prefer to not find a match in this case and leave the time formatted with seconds in such case.

提交回复
热议问题