Конвертировать строку в дату и изменить эту дату - PullRequest
0 голосов
/ 07 апреля 2020

Добрый день, я генерирую 3 даты из строки, я надеюсь, что результат был:

billing date: 2020/01/11
cutoff start: 2019/11/11
cuttof end: 2019/12/10

, но я получаю следующее:

billing date: 2020/11/10
cutoff start: 2019/11/10
cuttof end: 2019/12/10

Я хотел бы знать как javascript работает с переменными или в чем проблема, поскольку все меняется

var month = "Jan-20"
var coverage_month_obj = moment(month, 'MMM-YY').toDate();
var billing_date = new Date(coverage_month_obj.setDate(coverage_month_obj.getDate() + 10))
var cutoff_end = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
cutoff_end = new Date(billing_date.setDate(billing_date.getDate() - 1))
var cutoff_start = new Date(billing_date.setMonth(billing_date.getMonth() - 1))

1 Ответ

0 голосов
/ 07 апреля 2020

Я хотел бы знать, как javascript работает с переменными или в чем проблема, поскольку все изменяется

Проще говоря, вызывая setXXX для переменной даты javascript обновляет эту переменную на месте . ie, это то, что мы бы назвали "изменчивым". Возможно, вы предположили, что даты были неизменными и не менялись на месте.


Чтобы ответить на вопрос о лучшем способе достижения вашей цели, я бы предложил использовать другую функциональность момента js. чтобы вычислить ваши 3 даты из заданной входной строки.

var month = "Jan-20"
var coverage_month = moment(month, 'MMM-YY');

//Jan-20 I need to convert it into date format and that the day is 11 (2020/01/11) cutoff start, are two months less from that date (2020/11/11) and cutoff end is one month less from Jan-20, but ends on day 10 (2020/12/10)

var billing_date = coverage_month.clone().add(10, 'days');
var cutoff_start = billing_date.clone().subtract(2, 'months');
var cutoff_end = billing_date.clone().subtract(1,'months').subtract(1,'day')

console.log("billing_date",billing_date);
console.log('cutoff_start',cutoff_start);
console.log('cutoff_end',cutoff_end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
...