Как рассчитать дату в JavaScript, чтобы получить тот же день в месяце + некоторый месяц (переменная) - PullRequest
0 голосов
/ 28 февраля 2020

Кто-нибудь знает, как всегда установить дату на 28-й день текущего месяца или на 28-й день следующего месяца, если дата прошла 28-й день текущего месяца, а затем вычислить новую дату, используя переменную (количество месяцев). Вот как это было сделано. NET:

DateSerial(Year(DateAdd("m",
AmountOfMonths,
CDate(Invoice_date))),
Month(DateAdd(DateInterval.Month,
AmountOfMonths, CDate(Invoice_date))), 28)

Что я пробовал до сих пор:

var currentDate = new Date();
var day = currentDate.getDate() ;
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
if  (day <= "28") result += day ="28";
else result += day ="28";
if  (day > "28") result = month + "1";
results.html("<b>" + year + "/" + month + "/" + day + "</b>");

У меня уже есть проблема с настройкой в ​​следующем месяце, если день равен 29, 30 или 31. Затем мне нужно посчитать новую дату, добавив месяцы (5, 7 или 15 или просто любое число).

Ответы [ 3 ]

0 голосов
/ 29 февраля 2020

Чтобы добавить месяц, добавьте его к месяцу в дате. Вам нужно что-то сделать, только если дата больше 28, например

var currentDate = new Date();
var currentDay = currentDate.getDate() ;
currentDate.setDate(28);

if  (currentDay > 28) {
  currentDate.setMonth(currentDate.getMonth() + 1);
}

var month = currentDate.getMonth() + 1;
var year  = currentDate.getFullYear();

console.log(year + '/' + month + '/' + 28);
0 голосов
/ 10 марта 2020

Вот код, который работает для меня! Спасибо всем за помощь!

var field = "";
field = record.fields["CreditTime2"];
var currentDate = new Date();
var currentDay = currentDate.getDate() ;
currentDate.setDate(28);
if (currentDay > 28) { currentDate.setMonth(currentDate.getMonth() + 1);
}
//add number of months to already calculated date
currentDate.setMonth(currentDate.getMonth() + parseInt(field));
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
results.html(year + '-' + month + '-' + 28); 
0 голосов
/ 28 февраля 2020

Вы можете попробовать это, используя toLocaleDateString() и javascript Date методы получения и установки объекта:

// Returns a string in mm/dd/yyyy format
const GetFormattedDate = d => d.toLocaleDateString('en-US');

const CalculateDate = (dateStr) => {
  var currentDate = dateStr ? new Date(dateStr) : new Date();

  // Log the current actual date
  console.log('Actual date: ', GetFormattedDate(currentDate));

  var day = currentDate.getDate();
  if (day > 28) {
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  currentDate.setDate(28);

  // Return 28th of current or next month
  return GetFormattedDate(currentDate);
}

// 1 week ago
console.log('Updated date: ', CalculateDate('02/21/2020'))

// Today
console.log('Updated date: ', CalculateDate())

// 1 week later
console.log('Updated date: ', CalculateDate('03/06/2020'))

// 1 month later
console.log('Updated date: ', CalculateDate('03/29/2020'))

// 1 year later
console.log('Updated date: ', CalculateDate('02/21/2021'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
...