Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Add days to date

I found a piece of code which add days to the given date. However it only works when date is in YY-MM-DD format but it is not working if it is in DD-MM-YY format.

Fiddle for YY-MM-DD format (Working)

Fiddle for DD-MM-YY format (Not Working)

I further checked that if i do an alert for someDate.getDate() it says NaN Not A Number

someDate = new Date('27-08-2013');
alert(someDate.getDate()); //NaN 

Any help will be highly appreciated.

Upvotes: 1

Views: 445

Answers (2)

Jacobi
Jacobi

Reputation: 1524

I always create 7 functions, to work with date in JS: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears. They all work in any format.

You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/

How to use:

var now = new Date();
console.log(now.addWeeks(3));

This are the functions:

        Date.prototype.addSeconds = function(seconds) {
            this.setSeconds(this.getSeconds() + seconds);
            return this;
        };

        Date.prototype.addMinutes = function(minutes) {
            this.setMinutes(this.getMinutes() + minutes);
            return this;
        };

        Date.prototype.addHours = function(hours) {
            this.setHours(this.getHours() + hours);
            return this;
        };

        Date.prototype.addDays = function(days) {
            this.setDate(this.getDate() + days);
            return this;
        };

        Date.prototype.addWeeks = function(weeks) {
            this.addDays(weeks*7);
            return this;
        };

        Date.prototype.addMonths = function (months) {
            var dt = this.getDate();

            this.setMonth(this.getMonth() + months);
            var currDt = this.getDate();

            if (dt !== currDt) {  
                this.addDays(-currDt);
            }

            return this;
        };

        Date.prototype.addYears = function(years) {
            var dt = this.getDate();

            this.setFullYear(this.getFullYear() + years);

            var currDt = this.getDate();

            if (dt !== currDt) {  
                this.addDays(-currDt);
            }

            return this;
        };

Upvotes: 1

Jonathan Römer
Jonathan Römer

Reputation: 628

If your input is DD-MM-YY you can try to split the string. Check my fiddle:

http://jsfiddle.net/4RZAa/1/

I split the string and afterwards enter the desired format in the date function.

Upvotes: 0

Related Questions