简体   繁体   English

如何使用 javascript 获取 4 年 5 个月 3 天前的日期

[英]how to get what date was 4 years 5 months 3 days ago with javascript

I have 3 input text我有 3 个输入文本

  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?我知道如何获得 4 年前、5 个月前或 3 天前……但如何将其中三个结合起来?

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这里有一个使用内置Date object的方法。我们新建一个Date object代表当前日期,然后使用setFullYear()setMonth()方法分别减去指定的年数和月数,然后使用setDate()方法减去指定的天数

 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));

Basically, you wanted to deduct the year,month and day from current date?基本上,您想从当前日期中减去年月日? If yes, use date-fns.如果是,请使用 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>

Here is an example of how you can do it:以下是如何执行此操作的示例:

 function getDays() { const year = document.getElementById('year').value; const month = document.getElementById('month').value; const day = document.getElementById('day').value; console.log(`${year}year ${month}month ${day}day`); }
 <input class="form-control" id="year" name="year" type="text"> <input class="form-control" id="month" name="month" type="text"> <input class="form-control" id="day" name="day" type="text"> <input type="button" onclick="getDays();" value="click" />

I'm not sure what your question is but try this我不确定你的问题是什么,但试试这个

var year=getElementById('year');
var month=getElementById('month');
var day=getElementById('day');

var date = year+'-'+month+'-'+day;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM