简体   繁体   中英

How to initialize Date object in JavaScript

I'm trying to create Date object and do some basic operations with it like adding/subtraction, but something goes wrong. When I simply try to initialize that object with my date alert shows me 1970 year and so on (not my date at all).

Code:

function SmartDate(date) {

    this._workDate = new Date(date);

    this.add = function(days, symbol) {
        if(symbol == "d")
        {
            return this.setDate(this.getDate() + days);
        }
        else if(symbol == "m")
        {
            var dY = this.getFullYear();
            var dM = this.getMonth();
            return (dM+12*dY)+(2+12*dY);
        }
    }

    this.substract = function(hours) {
        if(hours > 0)
        {
            var diff = date.getTime() - hours;
            var hours = Math.floor(diff / 1000 / 60 / 60);
            diff -= hours * 1000 * 60 * 60;
            return diff;
        }
        else 
        {
            return date.getTime() - date.getTime();
        }

    }
    this.toDate = function() {
        return date;
    }
}
var a = new SmartDate(2008,7,7);
alert(a._workDate);

You're passing in 3 arguments - but only defining 1 argument - you need quotes around your arg!

var a = new SmartDate("2008,7,7");

(Your code was trying to execute new Date(2008) - which is invalid, so you get the default date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM