4

I want to get the before six months date using javascript.

I am using the following method.

var curr = date.getTime(); // i will get current date in milli seconds
var prev_six_months_date = curr - (6* 30 * 24 * 60* 60*1000);
var d = new Date();
d.setTime(prev_six_months_date);

Is this the right way or any better way to get the last six months date.

If this get fixed I want to apply this logic to get previous dates like last 2 months and last 10 years etc.

If any body give the solution in jquery also very helpful to me. Thanks in advance.

2
  • Since you tagged it jQuery, you can replace date.getTime() with $.now(). Commented Feb 8, 2012 at 12:12
  • It has been a long time since this question, but still : var d = new Date(); d.setMonth(d.getMonth()-6) Similarly, you can use setYears() and setDate() Commented Mar 22, 2015 at 18:38

3 Answers 3

6

Add more functionality to the Date

Date.prototype.addDays = function (n) {
    var time = this.getTime();
    var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
    this.setTime(changedDate.getTime());
    return this;
};

Usage

var date = new Date();
/* get month back */
date.addDays(-30);

/* get half a year back */
date.addDays(-30 * 6);

No need for extra libraries, if this is only thing you need regarding dates. You can also create more functions to the Date's prototype according to your needs.

Sign up to request clarification or add additional context in comments.

1 Comment

Great way to increase functionality.
1

I would look into date.js. It's well tested and has a very fluent interface for manipulating dates and times in JavaScript.

An example of using date.js:

(6).months().ago()

Comments

1

Try:

var curr = new Date();
var prev_six_months_date = new Date(curr);
var prev_two_months_date = new Date(curr);
var prev_ten_years_date = new Date(curr);
prev_six_months_date.setMonth(curr.getMonth() - 6);
prev_two_months_date.setMonth(curr.getMonth() - 2);
prev_ten_years_date.setFullYear(curr.getFullYear() - 10);
console.log(prev_six_months_date.toString());
console.log(prev_two_months_date.toString());
console.log(prev_ten_years_date.toString());
console.log(curr.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.