Getting previous date using Javascript

I want to get up to six months 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); 

This is the right way or the best way to get the last six months.

If this is fixed, I want to apply this logic to get previous dates, for example, last 2 months and last 10 years, etc.

If any body gives a solution in jquery, this is also very useful for me. Thanks in advance.

+4
source share
3 answers

Add functionality to 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; }; 

Using

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

No additional libraries are needed if it is only needed for dates. You can also create more Date prototype functions to suit your needs.

+6
source

I would look at date.js . It is well tested and has a very smooth interface for manipulating dates and times in JavaScript.

An example of using date.js:

 (6).months().ago() 
+1
source

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()); 
+1
source

Source: https://habr.com/ru/post/1395403/


All Articles