-2

I have 3 input text

  1. <input class="form-control" id="year" name="year" type="text">

  2. <input class="form-control" id="month" name="month" type="text">

  3. <input class="form-control" id="day" name="day" type="text">

I know how to get 4 years ago, or 5 month ago or 3 days ago.. but how to combine three of them?

  • please elaborate the question properly and what you wanted as a output – Sammed Jan 13 '23 at 06:16
  • how to combine them means you want 4 years+5month+3days back date ? – Sammed Jan 13 '23 at 06:17
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+find+date+days+months+years+ago+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jan 13 '23 at 06:20
  • Does this answer your question? [How to get 30 days prior to current date?](https://stackoverflow.com/questions/8842732/how-to-get-30-days-prior-to-current-date) – Tibrogargan Jan 13 '23 at 06:27
  • Getting the data of 4 years ago has nothing to deal with dom. please add more detail to your question – Eisa Rezaei Jan 13 '23 at 13:14

2 Answers2

1

Here's an approach using the built-in Date object. We create a new Date object representing the current date, and then use the setFullYear() and setMonth() methods to subtract the specified number of years and months, respectively, and then use setDate() method to subtract the specified number of days

const getPreviousDate = (years, months, days) => {
    const date = new Date();
    date.setFullYear(date.getFullYear() - years);
    date.setMonth(date.getMonth() - months);
    date.setDate(date.getDate() - days);

    return date;
};


console.log(getPreviousDate(1, 2, 10));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

Basically, you wanted to deduct the year,month and day from current date? If yes, use date-fns.

var sub = require('date-fns/sub')
var date = new Date()

var newDate = sub(date, {
  years: 5,
  months: 4,
  days: 2
}))
<script src="https://cdn.jsdelivr.net/npm/date-fns@2.29.3/index.min.js"></script>
Nani
  • 65
  • 6
  • 1
    Your script is not runnable here. OP would need to know how to make modules too – mplungjan Jan 13 '23 at 06:43
  • If you use a code snippet, be sure you test wether your code actually runs. The snippet you gave jist gives « script error ». Not very helpful to the OP. – Klaassiek Jan 14 '23 at 14:36