Search code examples
javascriptdateobject-literal

Stale javascript object literal date


Im trying to use a javascript object literal to format time in preporation for comparison to MySql datetime values.

Heres the object.

var dateTime = {
    d: new Date(),
    pad: function(number) {
        return (number < 10 ? '0' : '') + number;
    },
    now: function() {
        return this.d.getFullYear()+'-'+this.pad(this.d.getMonth()+1)+'-'+this.pad(this.d.getDate())+' '+this.pad(this.d.getHours())+':'+this.pad(this.d.getMinutes())+':'+this.pad(this.d.getSeconds());
    }            
}

Lets just say im calling this object onClick to get the date and display it in an alert box. I keep getting the same string returned.

Example:

alert(dateTime.now());

Returns:

Same date every time.

WHY?


Solution

  • Change your code to something like this:

    var dateTime = {
        pad: function(number) {
            return (number < 10 ? '0' : '') + number;
        },
        now: function() {
            var d = new Date();
            return d.getFullYear()+'-'+this.pad(d.getMonth()+1)+'-'+this.pad(d.getDate())+' '+this.pad(d.getHours())+':'+this.pad(d.getMinutes())+':'+this.pad(d.getSeconds());
        }            
    }
    

    When you do d: new Date(), you are taking an object which contains a date/time of a moment when new Date() is executed, like a snapshot. That object does not show dynamic time. And because of that you always have same time displayed. Actually, that is a time of when dateTime object created.