Convert a Unix timestamp to time in JavaScript

前端 未结 29 2152
渐次进展
渐次进展 2020-11-21 04:57

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/

29条回答
  •  情话喂你
    2020-11-21 05:22

    Based on @shomrat's answer, here is a snippet that automatically writes datetime like this (a bit similar to StackOverflow's date for answers: answered Nov 6 '16 at 11:51):

    today, 11:23
    

    or

    yersterday, 11:23
    

    or (if different but same year than today)

    6 Nov, 11:23
    

    or (if another year than today)

    6 Nov 2016, 11:23
    

    function timeConverter(t) {     
        var a = new Date(t * 1000);
        var today = new Date();
        var yesterday = new Date(Date.now() - 86400000);
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        var year = a.getFullYear();
        var month = months[a.getMonth()];
        var date = a.getDate();
        var hour = a.getHours();
        var min = a.getMinutes();
        if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
            return 'today, ' + hour + ':' + min;
        else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
            return 'yesterday, ' + hour + ':' + min;
        else if (year == today.getFullYear())
            return date + ' ' + month + ', ' + hour + ':' + min;
        else
            return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
    }
    

提交回复
热议问题