Updated

Автообновление дат

О шаблонах

Часто возникает потребность в установке авто обновление дат на лендингах.
Для этого есть готовые типы функций.

Авто обновление по дням

Если обновлять даты следующим способом - например, по вторникам выводим дату субботы, а в субботу показать дату следующего вторника, используй этот шаблон:

<script>
    const date = new Date();
    const dayWeek = [7, 1, 2, 3, 4, 5, 6][date.getDay()];
    const dayDate = date.getDate();

    // Все что нам нужно, задать только дни перевода в переменные day1, day2:
    // пн - 1, вт - 2, ср - 3, чт - 4, пт - 5, сб - 6, вс - 7

    // Если один из дней ВС - параметром в check*Number*Day нужно передать 
    // ("0" + date.getNextWeekDay(day*Number*.day, -1)
    // day*Number* == day1 || day2

    // В объекте day есть параметры времени time в который нужно указать время перевода


    const day1 = {
        day: 2,
        time: 1830
    }
    const day2 = {
        day: 6,
        time: 1230
    }

    const months = ['Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября',
        'Ноября', 'Декабря'
    ];

    Date.prototype.getMonthName = function () {
        return months[this.getMonth()];
    };

    Date.prototype.getNextWeekDay = function (day, increment) {
        if (day) {
            var nextMn = this;
            nextMn.setDate(this.getDate() - this.getDay() + increment + day);
            return nextMn;
        }
    };

    // data about current local time
    const currentMonth = ("0" + (date.getMonth() + 1)).slice(-2);
    const currentDay = ("0" + date.getDate()).slice(-2);
    const currentTime = ("0" + date.getHours()).slice(-2) + ("0" + date.getMinutes()).slice(-2);
    const currentDayWithTime = +(currentMonth + '' + currentDay + '' + currentTime);

    // data about check points time
    const checkFirstDay = +(currentMonth + ("0" + date.getNextWeekDay(day1.day, 0).getDate()).slice(-2) + day1.time);
    const checkSecondDay = +(currentMonth + ("0" + date.getNextWeekDay(day2.day, 0).getDate()).slice(-2) + day2.time);

    let autoDate = '';
    let month = '';

    // Check points by days
    if (currentDayWithTime < checkFirstDay) {
        let firstDayChange = date.getNextWeekDay(day1.day, 0);
        autoDate = firstDayChange.getDate();
        month = firstDayChange.getMonthName();
    } else if (currentDayWithTime > checkFirstDay && currentDayWithTime < checkSecondDay) {
        var nextDayChange = date.getNextWeekDay(day2.day, 0);
        autoDate = nextDayChange.getDate();
        month = nextDayChange.getMonthName();
    } else if (currentDayWithTime >= checkSecondDay) {
        var nextWeek = date.getNextWeekDay(day1.day, 7);
        autoDate = nextWeek.getDate();
        month = nextWeek.getMonthName();
    } else {
        autoDate = '';
    }

    if (autoDate < 10) {
        autoDate = `0${autoDate}`
    }

    // return right time
    var cDate = `${autoDate} ${month}`;
</script>

Автообновление по датам

Если обновлять даты следующим способом - используй этот шаблон:

<script>
//  У нас есть массив объектов с ключом перевода и строкой даты, которую нужно показать на лендинге
// key состоит из [5][31][1830]
// 5 - месяц
// 31 - дата
// 1830 - время

// Логика: при заходе на страницу скрипт вернет первый ключ, который больше чем реальное время
// И значение date запишется на страницу
const table = [
        {
            key: "5311830",
            date: "31 мая — 2 июня"
        }, 
        {
            key: "6071830",
            date: "7 — 9 июня"
        }, 
        {
            // lastElement
            key: "9999999",
            date: "05 июля — 07 июля"
        }
    ],
    date = new Date,
    currentTime = +(date.getMonth() + 1 + "" + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours()).slice(-2) + ("0" + date.getMinutes()).slice(-2)),
    found = table.find((e => e.key > currentTime));

    // return right time
    var cDate = found.date;
</script>

Ежедневое обновление даты

Если нужно обновлять даты каждый день после какого-то времени, используй этот шаблон:

<script>
   // Задаем время для перевода
   const timeToUpdate = '1830';

   const date = new Date();
   const dayWeek = [7, 1, 2, 3, 4, 5, 6][date.getDay()];
   const months = ['Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября',
       'Ноября', 'Декабря'
   ];

   Date.prototype.getMonthName = function () {
       return months[this.getMonth()];
   };

   // data about current local time
   const currentTime = +("0" + date.getHours()).slice(-2) + ("0" + date.getMinutes()).slice(-2);

   let autoDate = '';
   let month = '';
   let today = new Date();

   // Check points by time
   if (currentTime < +timeToUpdate) {
       autoDate = today.getDate();
       month = today.getMonthName();
   } else {
       let nextDay = new Date();
       nextDay.setDate(today.getDate() + 1);
       autoDate = nextDay.getDate();
       month = nextDay.getMonthName();
   }

   if (autoDate < 10) {
       autoDate = `0${autoDate}`
   }

   // return right time
   var cDate = `${autoDate} ${month}`;

</script>
Made with ❤&🍺 by @sonikbro