Convert a Unix timestamp to time in JavaScript

前端 未结 29 2172
渐次进展
渐次进展 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:33

    Pay attention to the zero problem with some of the answers. For example, the timestamp 1439329773 would be mistakenly converted to 12/08/2015 0:49.

    I would suggest on using the following to overcome this issue:

    var timestamp = 1439329773; // replace your timestamp
    var date = new Date(timestamp * 1000);
    var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
    console.log(formattedDate);
    

    Now results in:

    12/08/2015 00:49
    

提交回复
热议问题