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.

有帮助吗?

解决方案 2

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.)

其他提示

Moment.js is a great library for doing things like this.

moment(theDate).format('dd-mm-yyyy ; h:m:s');

It also supports getting dates back from strings:

moment('01-01-2001', 'dd-mm-yyyy');

Moment also has an extremely robust handling of the relative time statements you're doing manually:

moment(theDate).fromNow(); // 11 hours ago, in 3 days, etc.

Working with native date objects in Javascript can get tedious. Date math in general is hard. Moment wraps up all the hard work and lets you just describe what you want.

The javascript Date object has a toString() method, which will return a string representation of that date. However, if you aren't happy with the formatting of that string, there's no way to specify a specific format to use for the string -- you'd have to start pulling out the pieces of the date and building a string yourself.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top