Convert a Unix timestamp to time in JavaScript

Convert a Unix timestamp to time in JavaScript

Asked on November 28, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    This is the code for convert unix timestamp to time in javascript,

    // Create a new JavaScript Date object based on the timestamp
    // multiplied by 1000 so that the argument is in milliseconds, not seconds.
    var date = new Date(unix_timestamp*1000);
    // Hours part from the timestamp
    var hours = date.getHours();
    // Minutes part from the timestamp
    var minutes = "0" + date.getMinutes();
    // Seconds part from the timestamp
    var seconds = "0" + date.getSeconds();
    // Will display time in 10:30:23 format
    var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
    

    For further information prepare here, MDN and ECMAScript 5 specification.

    Answered on November 28, 2018.
    Add Comment

    That is pretty simple,

    The following code is used to convert the timestamp to time

    function timeConverter(UNIX_timestamp){
        var a = new Date(UNIX_timestamp * 1000);
        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();
        var sec = a.getSeconds();
        var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
        return time;
    }
    console.log(timeConverter(0));
    
    Answered on November 28, 2018.
    Add Comment

    Actually , this is very easy. Because,Javascript works within a seconds, so at first we have to convert timestamp into time,

    so the code is below,

    var date = new Date(UNIX_Timestamp * 1000);
    // Manipulate JavaScript Date object here...
    
    Answered on November 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.