If I understood the wording correctly, then:
- There is some text output like "The action lasts until DD.MM.YYYY"
- It is necessary to withdraw DD.MM.GG such that until the end of the action always remains from 4 to 1 day, but when this date comes - to extend the action for 4 days
As a result, the user will always see the "hot share", to the end of which less than 4 days are left, but there will be no obvious deception - within 4 days the share is up to the same number
Open the Javascript Date () class description in any google
For simplicity, we will use the day number in the month getDate() (not the most obvious name) for the start of the action (that is, from 1 to 4 numbers, from 5 to 9, from 10 to 14, and so on)
There is a current date. We need to know when the rally will end at the current date. Obviously, the next day, (number-1) of which will be completely divided by 4. Minus one because the numbering of days starts from 1, and numbers in mathematics start from 0.
/* Текущая дата и время */ var now = new Date(); /* Для отладки вы можете использовать не сегодняшнюю дату, а пример ниже */ // now = new Date(2017,4,14,2,31,30); alert('Сегодня '+now.toLocaleString()); /* До тех пор, пока (номер дня - 1) не делится нацело на 4, прибавляем 1 день к дате */ while ((now.getDate()-1) % 4 != 0) { now.setDate(now.getDate()+1); } alert('Акция закончится '+now.toLocaleString());
A more "scary" option, but a more reliable one is to count in seconds from the beginning of an epoch:
/* Текущая дата и время */ var now = new Date(); alert('Сегодня '+now.toLocaleString()); /* До тех пор, пока (номер дня - 1) не делится нацело на 4, прибавляем 1 день к дате */ var one_day = 1*24*60*60*1000; // Один день в миллисекундах var period = 4*24*60*60*1000; // Период обновления акции в миллисекунды // Прежде чем двигать время, надо округлить до целых суток, иначе имеем бесконечный цикл now.setTime(now.getTime() - now.getTime() % one_day); while ((now.getTime() % period) != 0) { now.setTime(now.getTime()+one_day); } alert('Акция закончится '+now.toLocaleString());
The logic is the same, only the 4 day block is translated into seconds. Subtleties - time zone