D
D
DeniSidorenko2019-02-15 10:49:48
JavaScript
DeniSidorenko, 2019-02-15 10:49:48

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>


How can I make JS calculate how many days are left before a given date? The date in this format is 03/01/2019 (taken from the database), but if required, you can change the date type (ex. 01/03/2019).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Michael, 2019-02-15
@DeniSidorenko

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) // количество целых дней до ожидаемого дня

N
NaN, 2019-02-15
@KornevaViktoria

moment.js

S
Sergey Sokolov, 2019-02-15
@sergiks

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 question

Ask a Question

731 491 924 answers to any question