Answer the question
In order to leave comments, you need to log in
How to calculate the number of days until a certain date?
There is a structure like this:
<div class="pg-info">
<div class="pg-info__top">Бронирование открыто до <span id="date">01.03.2019</span></div>
<div class="pg-info__bottom">осталось ВСЕГО <span class="number">45 </span><span>ДНЕЙ</span>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
You don’t have to drag third-party libraries, everything is solved with a couple of lines of code
let datestring = document.querySelector('#date').innerText; // получаем дату "Ч"
let regexp = /(\d{2})\.(\d{2})\.(\d{4})/;
let dateX = new Date(datestring.replace(regexp, '$2/$1/$3')); // парсим из нее дату с заменой строки в понятный JS формат (имеется в виду же 1 марта?)
let dateToday = new Date(); // дата на момент захода на страницу
let days = Math.floor((dateX - dateToday) / 86400000) // количество целых дней до ожидаемого дня
Split the string point by point into an array [дата, месяц, год]
, reset the hours, minutes, seconds, milliseconds of today's date to zero - so that the beginning of the day is also there. Calculate the difference of two dates in milliseconds, convert to a day:
function daysTill(ddmmyyyy) {
let dd, mm, yyyy;
[dd, mm, yyyy] = ddmmyyyy.split('.');
const Till = new Date(yyyy, mm-1, dd);
const Now = new Date();
return Math.floor((Till - Now) / 864e5);
}
daysTill("01.03.2019") // 13
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question