Convert date object to date string

I need to convert a date object to a string that SQL Server will understand. This is what I have so far:

(function() {
    Date.prototype.MMDDYYYY = function() {
        var month, day, year;
        month = String(this.getMonth() + 1);
        if (month.length === 1) {
            month = "0" + month;
        }
        day = String(this.getDate());
        if (day.length === 1) {
            day = "0" + day;
        }
        year = String(this.getFullYear());
        return month + '/' + day + '/' + year;
    }
})();

(function() {
    Date.prototype.HHMMSS = function() {
        var hour, minute, second;
        hour = String(this.getHours());
        minute = String(this.getMinutes());
        second = String(this.getSeconds());
        return '' + hour + ':' + minute + ':' + second;
    }
})();


function DateTimeFormat(objDate) {
    return objDate.MMDDYYYY() + ' ' + objDate.HHMMSS();
}

      

The error I'm getting is: Object Tue Jan 29 ... (Eastern Standard Time) doesn't have MMDDYYYY method.

It might be obvious, but I don't understand how the prototype is. Using jQuery is acceptable.

+3


source to share


2 answers


The problem is when you are passing a string to a function DateTimeFormat

.

You can guarantee it's a date object by adding this ...



objDate = new Date(objDate)

      

+1


source


I think the problem is not in scope, but how do you create objDate! I have made several attempts and this error occurs when objDate is a string. So this piece of code works as expected, the problem is with the parameter passed to DateTimeFormat: I think it was created like objDate = Date()

instead objDate = new Date()

. The latter will correctly create a Date object instead of a String-formatted return date.



+2


source







All Articles