Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Previous Date Using Javascript

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.

like image 268
user1049997 Avatar asked Feb 21 '23 13:02

user1049997


1 Answers

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.

like image 107
Tx3 Avatar answered Feb 27 '23 13:02

Tx3