2

I want to add 5 days to a date string in Javascript:

var olddate = '23.12.2013';
olddate = olddate.split('.');
var tmpDate = new Date(olddate[2],olddate[1],olddate[0]);
tmpDate.setDate(tmpDate.getDate() + 5);

var date = (tmpDate.getDate().toString().length < 2) ? '0' + 
    tmpDate.getDate() : tmpDate.getDate();

var month = (tmpDate.getMonth().toString().length < 2) ? '0' + 
    tmpDate.getMonth() : tmpDate.getMonth();

console.log( date + '.'  + month + '.'+ tmpDate.getFullYear());

This code shows 27.00.2014 instead of what I expect: 27.12.2013. I would like to add 5 days to the String date. Why is this off by a month?

Mirco
  • 2,940
  • 5
  • 34
  • 57
julesdude
  • 195
  • 1
  • 2
  • 16

4 Answers4

2

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

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;
        };
Jacobi
  • 1,508
  • 15
  • 29
1

The Date constructor takes numeric months from 0 to 11, not 1 to 12 so you are off by a month when you do this:

var olddate = '23.12.2013';
// Calculate new date
olddate = olddate.split('.');
var tmpDate = new Date(olddate[2],olddate[1],olddate[0]);

You can correct for that, by doing this:

var tmpDate = new Date(+olddate[2], +olddate[1] - 1, +olddate[0]);

Working demo: http://jsfiddle.net/jfriend00/Aa4P7/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • If I take this, the result would be 27.11.2013 but it sould be 27.12.2013 – julesdude Jan 08 '14 at 09:09
  • @julesdude - you don't seem to understand. Try it. It works. Months are passed as `0 to `11 so December must be passed as 11 not as 12. Working demo: http://jsfiddle.net/jfriend00/Aa4P7/ – jfriend00 Jan 08 '14 at 16:17
1

Very Simple Approach would be using .setDate()

var olddate = '23.12.2013';
// Calculate new date
olddate = olddate.split('.');
var tmpDate = new Date(olddate[2],olddate[1]-1,olddate[0]);
var numberOfDaysToAdd = 6;
tmpDate .setDate(tmpDate .getDate() + numberOfDaysToAdd); 

But i would recommand you to use Moment.js. Using this you can manipulate date time any way you want.

EDIT:

In your example problem is that Javascript Date() month starts from 0. So for Example if you do

var abc = new Date();
console.log(abc.getMonth());

you will get output 0 for current January month, not 1.

So take this into consideration and you will get correct results.

Aks
  • 1,567
  • 13
  • 23
0

I've used this for many times:

You can pass three arguments:
1. time(The time to be added) Notice: You need to pass a Date instead of a String.
2. type(You want to add "hour" or "day" or "moneth" or "year")
3. n(How many times do you want to add? Default will be 1, If the type is "hour", that means you want to add 1 hour, etc. )

calNByDateType : function(time, type) {

  var myTime = new Date( time.valueOf() );
  var n = 1;
  if(arguments[2]!==undefined) {
    n=arguments[2];
  }
  if(type==="hour") {
    myTime.setHours( myTime.getHours() + n );
  } else if(type==="day") {
    myTime.setDate( myTime.getDate() + n );
  } else if(type==="month") {
    myTime.setMonth( myTime.getMonth() + n );
  } else if(type==="year") {
    myTime.setFullYear( myTime.getFullYear() + n );
  }

  return myTime;
}
Liber
  • 422
  • 4
  • 12