簡體   English   中英

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

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

我有 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">

我知道如何獲得 4 年前、5 個月前或 3 天前……但如何將其中三個結合起來?

這里有一個使用內置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));

基本上,您想從當前日期中減去年月日? 如果是,請使用 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>

以下是如何執行此操作的示例:

 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" />

我不確定你的問題是什么,但試試這個

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