将Unix时间戳转换为小时:分钟AM / PM?

时间:2019-07-03 04:00:45

标签: javascript

我已经进行了转换,但是问题是我不知道如何添加上午/下午。

我的解决方案

var unixtimestamp = "1560994096411";
var date = new Date(unixtimestamp);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var convdataTime = hours + ':' + minutes.substr(-2);
console.log(convdataTime);

我明白了

  

9:28

2 个答案:

答案 0 :(得分:2)

您可以根据需要使用momentjs库

var unixtimestamp = 1560994096411;
let result = moment.unix(unixtimestamp).format('hh:mm A'); // 10 digit
let result = moment(unixtimestamp).format('hh:mm A'); // 13 digit
console.log(result);

var unixtimestamp = 1560994096411;
let result = moment(unixtimestamp).format('hh:mm A');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>

答案 1 :(得分:0)

<script>

    function formatAMPM(UNIX_timestamp) {

        var date = new Date(UNIX_timestamp * 1000);

        var hours = date.getHours();
        var minutes = date.getMinutes();
        var secends = date.getSeconds();

        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        secends = secends < 10 ? '0' + secends : secends;
        var strTime = hours + ':' + minutes + ':' + secends + ' ' + ampm;

        return strTime;
    }

    console.log(formatAMPM(1560994096));

</script>