簡體   English   中英

如何在 JavaScript 中為當前日期和格式添加天數?

[英]How to add days to a current date and format in JavaScript?

我想制作一個需要今天日期並添加更多天數的函數。 例如,如果今天的日期是 10/09/20 並且我添加了 5 天,我想返回 15/09/20。

我想這樣格式化結果:

9月15日

我創建了以下函數:

function calcDate(days){
  var curDate = new Date();
  
  var estDate = curDate.setDate(curDate.getDate() + days);
 
  return estDate.getDate() + ' ' + estDate.getMonth();
}

但是,我收到錯誤estDate.getDate() is not a function

如果我只返回estDate我也會得到一個未格式化的數字,例如: 1608685587862

我嘗試了來自 Google 和 Stack Overflow 的幾種方法,但都沒有奏效。

有誰知道我要做什么?

Date.prototype.setDate返回結果的毫秒數,它是一個數字,而不是Date對象。

您還可以將這些天的等效毫秒數添加到當前時間以計算所需的日期:

 function calcDate(days){ var curDate = new Date(); var estDate = new Date(curDate.getTime() + days * 24 * 60 * 60 * 1000); return estDate.toLocaleDateString('en-GB', { month: 'short', day: 'numeric' }); } console.log(calcDate(5));

差不多好了! 您正在使用正確的日期方法: .setDate() 這只是剩下的格式。 您可以使用 Moment JS 來格式化日期。

 function calcDate(days){ var curDate = new Date(); var estDate = curDate.setDate(curDate.getDate() + days); return moment(estDate).format('DD/MM/YY'); } console.log( calcDate( 5 ) ); console.log( calcDate( 10 ) ); console.log( calcDate( 20 ) );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>

setDate() 將以毫秒為單位返回日期值,您需要再次將其解析為日期。 在您的示例中,您無需使用額外的變量“estdate”,您可以在設置日期后使用“ curDate ”變量。

注意: Date.getMonth() 將返回從零開始的月份,即 9 月它將返回 8。

function calcDate(days){
  var curDate = new Date(); 
 curDate.setDate(curDate.getDate() + days); 
  return curDate.getDate() + ' ' + (curDate.getMonth()+1);
}
console.log(calcDate(1));

這是演示(請參閱 JavaScript 選項卡)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM