Search code examples
javascriptdateutcgettime

How to convert date received from getTime() method to DD-MM-YYYY format?


My problem is simple yet so hard for me to solve. Basically I am storing the number received from the new Date().getTime() method in the database and then using that string in a time ago function. The function works very well but I don't know how to convert the string back to a DD-MM-YYYY ; h:m:s format

my time ago function:

<script>
$(document).ready(function() {
var db_time = //the string from the database;
var c_db_time = db_time/1000;//remove the milli seconds
function ago()
{
    var current_time = new Date().getTime()/1000;//remove the milli seconds
    var dif = Math.round(current_time - c_db_time);
    if(dif<60)//one minute ago
    {
        if(dif<=10){$(".elapsed_time").html("just now");}
        else{var ago = dif;$(".elapsed_time").html(ago+"sec ago");}
    }

    else if(dif<3600)//one hour ago
    {
        var ago = Math.round(dif/60);
        $(".elapsed_time").html(ago+"min ago")
    }
    else if(dif<86400)//one day ie.24hours ago
    {
        var ago = Math.round(dif/3600);
        $(".elapsed_time").html(ago+"hr ago");
    }
    else if(dif<604800)// one week ago
    {
        var ago = Math.round(dif/86400);
        $(".elapsed_time").html(ago+"Day ago");
    }

}
setInterval(ago,1000);//run the script every 1 sec
});
</script>

Note: I researched everywhere on google and stack overflow but could not find an answer that works for me.


Solution

  • You can construct a Date instance from a timestamp value and then use the various accessor methods (.getDate(), .getMonth(), .getFullYear() etc) to format the date according to your needs.

    So for example:

    var savedDate = new Date(db_time);
    

    to make a Date instance. Then it's helpful to have a function to produce two-digit zero-prefixed numbers:

    function d2( n ) {
      return (n < 10 ? "0" : "") + n;
    }
    

    Then a DD-MM-YYYY date can be built:

    var ddmmyy = d2(savedDate.getDate()) + "-" + d2(savedDate.getMonth() + 1) + "-" + savedDate.getFullYear();
    

    (The month values from Date instances run 0 to 11, thus the need to add 1.)