Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   возможно ли получить число(дату) события? (https://javascript.ru/forum/misc/83483-vozmozhno-li-poluchit-chislo-datu-sobytiya.html)

Блондинка 20.12.2021 17:20

возможно ли получить число(дату) события?
 
есть такой скрипт

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            #holiday {
                display: none;
                background: hsl(0, 0%, 90%);
                border: 1px solid hsl(0, 0%, 50%);
                border-radius: 12px/9px;
            }
            .public_holiday {
                color: hsl(340, 100%, 50%);
            }
            .holiday {
                color: hsl(210, 100%, 50%);
            }
            .birthday {
                color: hsl(120, 100%, 25%);
            }
            #holiday,
            .public_holiday,
            .holiday,
            .birthday {
                display: block;
                font: bold 24px/20px serif;
                text-align: center;
                padding: 15px 20px;
            }
        </style>
    </head>
    <body>
        <div id="header">
            <div id="logo"></div>
            <div id="block_time-data"></div>
        </div>
        <div id="holiday"></div>
        <script>
            var holidays = [
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "С новым годом !",
                    },
                    7: {
                        start: 0,
                        duration: 24,
                        compliments: "С рождеством !",
                    },
                },
                {
                    23: {
                        start: 0,
                        duration: 24,
                        compliments: "С 23 февраля !",
                    },
                },
                {
                    8: { start: 0, duration: 24, compliments: "С 8 марта !" },
                },
                {
                    12: {
                        start: 0,
                        duration: 24,
                        compliments: "С днём космонавтики !",
                    },
                },
                {
                    1: { start: 0, duration: 24, compliments: "С 1 мая !" },
                    2: [
            // Если праздников несколько, то в массив
            // Строка class="***" должна задаваться в ", а не в '
                        {
                            start: 6,
                            duration: 24 * 7 - 6,
                            compliments:
                                '<span class="birthday">С ДНЮХОЙ !</span>',
                        },
                        {
                            start: 0,
                            duration: 24,
                            compliments:
                                '<span class="holiday">С 2 мая !</span>',
                        },
                    ],
                    9: { start: 0, duration: 24, compliments: "С 9 мая !" },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "С 1 июня, Всемирным днём родителей !",
                    },
                },
                {
                    3: {
                        start: 0,
                        duration: 24,
                        compliments:
                            "3 июля, день независимости Республики Беларусь !",
                    },
                },
                {
                    12: {
                        start: 0,
                        duration: 24,
                        compliments: "12 августа международный день молодёжи !",
                    },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "1 сентября, день знаний !",
                    },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments:
                            "1 октября, международный день пожилых людей !",
                    },
                },
                {
                    7: {
                        start: 0,
                        duration: 24,
                        compliments: "7 ноября, день октябрьской революции !",
                    },
                },
                {
                    25: {
                        start: 0,
                        duration: 24,
                        compliments: "С католическим рождеством !",
                    },
                },
            ];
 
            function catholicDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var k = Math.floor(year / 100);
                var p = Math.floor((13 + 8 * k) / 25);
                var q = Math.floor(k / 4);
                var m = (15 - p + k - q) % 30;
                var n = (4 + k - q) % 7;
                var d = (19 * a + m) % 30;
                var e = (2 * b + 4 * c + 6 * d + n) % 7;
                if (d === 29 && e === 6) return new Date(year, 3, 19);
                if (d === 28 && e === 6 && (11 * m + 11) % 30 < 19)
                    return new Date(year, 3, 18);
                if (d + e > 9) return new Date(year, 3, d + e - 9);
                else return new Date(year, 2, 22 + d + e);
            }
 
            function orthodoxDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var d = (19 * a + 15) % 30;
                var e = (2 * b + 4 * c + 6 * d + 6) % 7;
                var f = d + e;
                return f <= 26
                    ? new Date(year, 3, 4 + f)
                    : new Date(year, 4, f - 26);
            }
 
            const today = new Date("2 May 2021 07:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )
 
            function getActualCompliments(now) {
                const result = [];
                holidays.forEach((vm, month) => {
                    for (const day in vm) {
                        let hlds = vm[day];
                        if (!Array.isArray(hlds)) hlds = [hlds];
                        for (const hld of hlds) {
                            const currentDate = new Date(
                                now.getFullYear(),
                                month,
                                +day,
                                +hld.start
                            );
                            const rg = now.getTime() - currentDate.getTime();
                            if (0 <= rg && rg < hld.duration * 3600000) {
                                result.push(hld.compliments);
                            }
                        }
                    }
                });
 
                const caholic = catholicDate(now.getFullYear());
                const ortodox = orthodoxDate(now.getFullYear());
 
                if (
                    caholic.getMonth() == now.getMonth() &&
                    caholic.getDate() == now.getDate()
                )
                    result.push("С католической пасхой!");
 
                if (
                    ortodox.getMonth() == now.getMonth() &&
                    ortodox.getDate() == now.getDate()
                )
                    result.push('<span class="public_holiday">С православной пасхой!</span>');
 
                const radunitsa = new Date(ortodox);
                radunitsa.setDate(radunitsa.getDate() + 9);
                if (
                    radunitsa.getMonth() == now.getMonth() &&
                    radunitsa.getDate() == now.getDate()
                )
                    result.push("С радуницей !");
 
                const trinity = new Date(ortodox);
                trinity.setDate(trinity.getDate() + 49);
                if (
                    trinity.getMonth() == now.getMonth() &&
                    trinity.getDate() == now.getDate()
                )
                    result.push("С троицей!");
 
                return result;
            }
 
            const actualCompliments = getActualCompliments(today);
 
            console.log(actualCompliments);
 
            if (actualCompliments.length > 0) {
                const hollyday = document.getElementById("holiday");
                hollyday.style.display = "block";
                for (const cl of ["public_holiday", "holiday", "birthday"]) {
                    for (const c of actualCompliments) {
                        if (c.indexOf('class="' + cl + '"')>=0) {
                            const div = document.createElement("div");
                            hollyday.appendChild(div);
                            div.innerHTML = c;
                        }
                    }
                }
            }
        </script>
        <div id="footer"></div>
    </body>
</html>

Блондинка 20.12.2021 17:20

возможно ли в него добавить плавающие события, где известен месяц, день недели и порядковый номер недели с начала или конца месяца?

что нибудь, типа добавить функцию

return { month: holiday.month, day: days[index] };


Затем объекты таких "плавающих" событий свести в отдельный массив, и тогда в функции getActualCompliments можно вызвать функцию getDate для каждого из них...
массив будет выглядеть примерно так:

const holidays_2 = [
  {
      month: 5, 
      day: 7, 
      number: 1, 
      compliments: "<span class='birthday'>именины Иван</span>",
  },
{
      month: 5, 
      day: 7, 
      number: -5, 
      compliments: "<span class='birthday'>именины Виктор</span>",
  }
]


а потом проверять типа
for (let holiday of holidays_2) {
  const d = getDate(holiday);
  if (d.month == now.getMonth() && d.day == now.getDate()) {
    result.push(holiday.compliments);
  }
}


подобное возможно на JS ?

ksa 20.12.2021 21:12

Цитата:

Сообщение от Блондинка
возможно ли в него добавить плавающие события, где известен месяц, день недели и порядковый номер недели с начала или конца месяца?
...
подобное возможно на JS ?

Да, возможно. :yes:

voraa 20.12.2021 21:12

Все возможно. Но текст стал слишком большим, и форум не принимает его. Поэтому убрал некоторые праздники
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            #holiday {
                display: none;
                background: hsl(0, 0%, 90%);
                border: 1px solid hsl(0, 0%, 50%);
                border-radius: 12px/9px;
            }
            .public_holiday {
                color: hsl(340, 100%, 50%);
            }
            .holiday {
                color: hsl(210, 100%, 50%);
            }
            .birthday {
                color: hsl(120, 100%, 25%);
            }
            #holiday,
            .public_holiday,
            .holiday,
            .birthday {
                display: block;
                font: bold 24px/20px serif;
                text-align: center;
                padding: 15px 20px;
            }
        </style>
    </head>
    <body>
        <div id="header">
            <div id="logo"></div>
            <div id="block_time-data"></div>
        </div>
        <div id="holiday"></div>
        <script>
            var holidays = [
                {
                },
                {
                    23: {
                        start: 0,
                        duration: 24,
                        compliments: "С 23 февраля !",
                    },
                },
                {
                    8: { start: 0, duration: 24, compliments: "С 8 марта !" },
                },
                {
                    12: {
                        start: 0,
                        duration: 24,
                        compliments: "С днём космонавтики !",
                    },
                },
                {
                    1: { start: 0, duration: 24, compliments: "С 1 мая !" },
                    2: [
            // Если праздников несколько, то в массив
            // Строка class="***" должна задаваться в ", а не в '
                        {
                            start: 6,
                            duration: 24 * 7 - 6,
                            compliments:
                                '<span class="birthday">С ДНЮХОЙ !</span>',
                        },
                        {
                            start: 0,
                            duration: 24,
                            compliments:
                                '<span class="holiday">С 2 мая !</span>',
                        },
                    ],
                    9: { start: 0, duration: 24, compliments: "С 9 мая !" },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "С 1 июня, Всемирным днём родителей !",
                    },
                },
                {
                    3: {
                        start: 0,
                        duration: 24,
                        compliments:
                            "3 июля, день независимости Республики Беларусь !",
                    },
                },
                {
                },
                {
                },
                {
                },
                {
                },
                {
                },
            ];
            
// =================== Добавил                       
 // Добавить праздники           
    addHolyday(3, 0, 2,    // второе воскресенье апреля
		{        
			start: 0,
			duration: 24,
			compliments: '<span class="holiday">С днем ПВО</span>',
		}
	)
		
// =================== Добавил             
// Вычисляет число соответствующее дню недели в месяце
// month - месяц (0-11)
// wday - день недели 0 - воскр, 1 - понед ....
// index 1 первый день, 2 - второй ... -1 - последний, -2 предпоследний
            function dayNWeek (month, wday, index)  {
				const wday1 = new Date(new Date().getFullYear(), month).getDay()
				const dd = wday - wday1
				let dayw = 1 + (dd >= 0? dd : 7 + dd);
				const dtwday = new Date(new Date().getFullYear(), month, dayw)
				const adayw =[]
				while (new Date(new Date().getFullYear(), month, dayw).getMonth() == month) {
					adayw.push(dayw)
					dayw += 7
				}
				return adayw[(index>0)? index-1 : adayw.length + index]
			}
// добавляет праздник в массив holidays
			function addHolyday (month, wday, index, hobj) {
				const dt = dayNWeek (month, wday, index);
				holidays[month][dt] = hobj;
			}
// ========================================			
            function catholicDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var k = Math.floor(year / 100);
                var p = Math.floor((13 + 8 * k) / 25);
                var q = Math.floor(k / 4);
                var m = (15 - p + k - q) % 30;
                var n = (4 + k - q) % 7;
                var d = (19 * a + m) % 30;
                var e = (2 * b + 4 * c + 6 * d + n) % 7;
                if (d === 29 && e === 6) return new Date(year, 3, 19);
                if (d === 28 && e === 6 && (11 * m + 11) % 30 < 19)
                    return new Date(year, 3, 18);
                if (d + e > 9) return new Date(year, 3, d + e - 9);
                else return new Date(year, 2, 22 + d + e);
            }
  
            function orthodoxDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var d = (19 * a + 15) % 30;
                var e = (2 * b + 4 * c + 6 * d + 6) % 7;
                var f = d + e;
                return f <= 26
                    ? new Date(year, 3, 4 + f)
                    : new Date(year, 4, f - 26);
            }
  
//            const today = new Date("2 May 2021 07:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )
const today = new Date (2021, 3, 11)  // ======== Изменил для теста ======
  
            function getActualCompliments(now) {
                const result = [];
                holidays.forEach((vm, month) => {
                    for (const day in vm) {
                        let hlds = vm[day];
                        if (!Array.isArray(hlds)) hlds = [hlds];
                        for (const hld of hlds) {
                            const currentDate = new Date(
                                now.getFullYear(),
                                month,
                                +day,
                                +hld.start
                            );
                            const rg = now.getTime() - currentDate.getTime();
                            if (0 <= rg && rg < hld.duration * 3600000) {
                                result.push(hld.compliments);
                            }
                        }
                    }
                });
  
                const caholic = catholicDate(now.getFullYear());
                const ortodox = orthodoxDate(now.getFullYear());
  
                if (
                    caholic.getMonth() == now.getMonth() &&
                    caholic.getDate() == now.getDate()
                )
                    result.push("С католической пасхой!");
  
                if (
                    ortodox.getMonth() == now.getMonth() &&
                    ortodox.getDate() == now.getDate()
                )
                    result.push('<span class="public_holiday">С православной пасхой!</span>');
  
                const radunitsa = new Date(ortodox);
                radunitsa.setDate(radunitsa.getDate() + 9);
                if (
                    radunitsa.getMonth() == now.getMonth() &&
                    radunitsa.getDate() == now.getDate()
                )
                    result.push("С радуницей !");
  
                const trinity = new Date(ortodox);
                trinity.setDate(trinity.getDate() + 49);
                if (
                    trinity.getMonth() == now.getMonth() &&
                    trinity.getDate() == now.getDate()
                )
                    result.push("С троицей!");
  
                return result;
            }
  
            const actualCompliments = getActualCompliments(today);
  
            console.log(actualCompliments);
  
            if (actualCompliments.length > 0) {
                const hollyday = document.getElementById("holiday");
                hollyday.style.display = "block";
                for (const cl of ["public_holiday", "holiday", "birthday"]) {
                    for (const c of actualCompliments) {
                        if (c.indexOf('class="' + cl + '"')>=0) {
                            const div = document.createElement("div");
                            hollyday.appendChild(div);
                            div.innerHTML = c;
                        }
                    }
                }
            }
        </script>
        <div id="footer"></div>
    </body>
</html>

Блондинка 21.12.2021 13:40

voraa,
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            #holiday {
                display: none;
                background: hsl(0, 0%, 90%);
                border: 1px solid hsl(0, 0%, 50%);
                border-radius: 12px/9px;
            }
            .public_holiday {
                color: hsl(340, 100%, 50%);
            }
            .holiday {
                color: hsl(210, 100%, 50%);
            }
            .birthday {
                color: hsl(120, 100%, 25%);
            }
            #holiday,
            .public_holiday,
            .holiday,
            .birthday {
                display: block;
                font: bold 24px/20px serif;
                text-align: center;
                padding: 15px 20px;
            }
        </style>
    </head>
    <body>
        <div id="header">
            <div id="logo"></div>
            <div id="block_time-data"></div>
        </div>
        <div id="holiday"></div>
        <script>
            var holidays = [
                {
                },
                {
                    23: {
                        start: 0,
                        duration: 24,
                        compliments: "С 23 февраля !",
                    },
                },
                {
                    8: { start: 0, duration: 24, compliments: "С 8 марта !" },
                },
                {
                    12: {
                        start: 0,
                        duration: 24,
                        compliments: "С днём космонавтики !",
                    },
                },
                {
                    1: { start: 0, duration: 24, compliments: "С 1 мая !" },
                    2: [
            // Если праздников несколько, то в массив
            // Строка class="***" должна задаваться в ", а не в '
                        {
                            start: 6,
                            duration: 24 * 7 - 6,
                            compliments:
                                '<span class="birthday">С ДНЮХОЙ !</span>',
                        },
                        {
                            start: 0,
                            duration: 24,
                            compliments:
                                '<span class="holiday">С 2 мая !</span>',
                        },
                    ],
                    9: { start: 0, duration: 24, compliments: "С 9 мая !" },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "С 1 июня, Всемирным днём родителей !",
                    },
                },
                {
                    3: {
                        start: 0,
                        duration: 24,
                        compliments:
                            "3 июля, день независимости Республики Беларусь !",
                    },
                },
                {
                },
                {
                },
                {
                },
                {
                },
                {
                },
            ];
            
// =================== Добавил
    addHolyday(4, 0, 1,    // первое воскресенье мая
		{        
			start: 0,
			duration: 24,
			compliments: '<span class="holiday">именины Виктор</span>',
		}),
	(4, 0, -5,    // первое воскресенье мая
		{        
		start: 0,
		duration: 24,
		compliments: '<span class="holiday">именины Иван</span>',
		}
	)
		
// =================== Добавил             
// Вычисляет число соответствующее дню недели в месяце
// month - месяц (0-11)
// wday - день недели 0 - воскр, 1 - понед ....
// index 1 первый день, 2 - второй ... -1 - последний, -2 предпоследний
            function dayNWeek (month, wday, index)  {
				const wday1 = new Date(new Date().getFullYear(), month).getDay()
				const dd = wday - wday1
				let dayw = 1 + (dd >= 0? dd : 7 + dd);
				const dtwday = new Date(new Date().getFullYear(), month, dayw)
				const adayw =[]
				while (new Date(new Date().getFullYear(), month, dayw).getMonth() == month) {
					adayw.push(dayw)
					dayw += 7
				}
				return adayw[(index>0)? index-1 : adayw.length + index]
			}
// добавляет праздник в массив holidays
			function addHolyday (month, wday, index, hobj) {
				const dt = dayNWeek (month, wday, index);
				holidays[month][dt] = hobj;
			}
// ========================================			
            function catholicDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var k = Math.floor(year / 100);
                var p = Math.floor((13 + 8 * k) / 25);
                var q = Math.floor(k / 4);
                var m = (15 - p + k - q) % 30;
                var n = (4 + k - q) % 7;
                var d = (19 * a + m) % 30;
                var e = (2 * b + 4 * c + 6 * d + n) % 7;
                if (d === 29 && e === 6) return new Date(year, 3, 19);
                if (d === 28 && e === 6 && (11 * m + 11) % 30 < 19)
                    return new Date(year, 3, 18);
                if (d + e > 9) return new Date(year, 3, d + e - 9);
                else return new Date(year, 2, 22 + d + e);
            }
  
            function orthodoxDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var d = (19 * a + 15) % 30;
                var e = (2 * b + 4 * c + 6 * d + 6) % 7;
                var f = d + e;
                return f <= 26
                    ? new Date(year, 3, 4 + f)
                    : new Date(year, 4, f - 26);
            }
  
//            const today = new Date("2 May 2021 07:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )
const today = new Date (2021, 4, 2)  // ======== Изменил для теста ======
  
            function getActualCompliments(now) {
                const result = [];
                holidays.forEach((vm, month) => {
                    for (const day in vm) {
                        let hlds = vm[day];
                        if (!Array.isArray(hlds)) hlds = [hlds];
                        for (const hld of hlds) {
                            const currentDate = new Date(
                                now.getFullYear(),
                                month,
                                +day,
                                +hld.start
                            );
                            const rg = now.getTime() - currentDate.getTime();
                            if (0 <= rg && rg < hld.duration * 3600000) {
                                result.push(hld.compliments);
                            }
                        }
                    }
                });
  
                const caholic = catholicDate(now.getFullYear());
                const ortodox = orthodoxDate(now.getFullYear());
  
                if (
                    caholic.getMonth() == now.getMonth() &&
                    caholic.getDate() == now.getDate()
                )
                    result.push("С католической пасхой!");
  
                if (
                    ortodox.getMonth() == now.getMonth() &&
                    ortodox.getDate() == now.getDate()
                )
                    result.push('<span class="public_holiday">С православной пасхой!</span>');
  
                const radunitsa = new Date(ortodox);
                radunitsa.setDate(radunitsa.getDate() + 9);
                if (
                    radunitsa.getMonth() == now.getMonth() &&
                    radunitsa.getDate() == now.getDate()
                )
                    result.push("С радуницей !");
  
                const trinity = new Date(ortodox);
                trinity.setDate(trinity.getDate() + 49);
                if (
                    trinity.getMonth() == now.getMonth() &&
                    trinity.getDate() == now.getDate()
                )
                    result.push("С троицей!");
  
                return result;
            }
  
            const actualCompliments = getActualCompliments(today);
  
            console.log(actualCompliments);
  
            if (actualCompliments.length > 0) {
                const hollyday = document.getElementById("holiday");
                hollyday.style.display = "block";
                for (const cl of ["public_holiday", "holiday", "birthday"]) {
                    for (const c of actualCompliments) {
                        if (c.indexOf('class="' + cl + '"')>=0) {
                            const div = document.createElement("div");
                            hollyday.appendChild(div);
                            div.innerHTML = c;
                        }
                    }
                }
            }
        </script>
        <div id="footer"></div>
    </body>
</html>

Блондинка 21.12.2021 13:59

voraa,
для теста установила 2 мая 2021г, когда была пасха, и чей-та не очень хорошо работает, ведь главное чтобы все события за этот день показывались, по идее должно быть 5 событий, пасха, с 2 мая, с днюхой, и два добавленных события именины Виктор, именины Иван...

но не все события видны...

voraa 21.12.2021 15:06

1. Функцию addHolyday (строки 142-146) записать так

// добавляет праздник в массив holidays
            function addHolyday (month, wday, index, hobj) {
                const dt = dayNWeek (month, wday, index);
                if (holidays[month][dt]) {
					if (!Array.isArray(holidays[month][dt])) 
						holidays[month][dt] = [holidays[month][dt]];
                } else {
					holidays[month][dt] = [];
                }
                holidays[month][dt].push(hobj);
            }


2. Ее вызов (строки 111 - 123) должен быть таким
addHolyday(4, 0, 1,    // первое воскресенье мая
        {       
            start: 0,
            duration: 24,
            compliments: '<span class="holiday">именины Виктор</span>',
        });
    addHolyday(4, 0, -5,    // первое воскресенье мая
        {       
        start: 0,
        duration: 24,
        compliments: '<span class="holiday">именины Иван</span>',
        }
    );

Т.е для добаления каждого праздника ее надо вызывать, а не нескольких сразу

addHolyday(4, 0, -5, // первое воскресенье мая
Не каждый год в мае 5 воскресений, поэтому лучше addHolyday(4, 0, 1
Но в этом году и -5 работает

Блондинка 21.12.2021 15:19

Цитата:

Сообщение от voraa
addHolyday(4, 0, -5, // первое воскресенье мая
Не каждый год в мае 5 воскресений, поэтому лучше addHolyday(4, 0, 1
Но в этом году и -5 работает


это понятно, ведь это сделала чисто для тестирования, пойду пробовать...

Блондинка 21.12.2021 15:30

чисто проверить, что отсчёт индекса идёт от конца месяца...

Блондинка 21.12.2021 15:37

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            #holiday {
                display: none;
                background: hsl(0, 0%, 90%);
                border: 1px solid hsl(0, 0%, 50%);
                border-radius: 12px/9px;
            }
            .public_holiday {
                color: hsl(340, 100%, 50%);
            }
            .holiday {
                color: hsl(210, 100%, 50%);
            }
            .birthday {
                color: hsl(120, 100%, 25%);
            }
            #holiday,
            .public_holiday,
            .holiday,
            .birthday {
                display: block;
                font: bold 24px/20px serif;
                text-align: center;
                padding: 15px 20px;
            }
        </style>
    </head>
    <body>
        <div id="header">
            <div id="logo"></div>
            <div id="block_time-data"></div>
        </div>
        <div id="holiday"></div>
        <script>
            var holidays = [
                {
                },
                {
                    23: {
                        start: 0,
                        duration: 24,
                        compliments: "С 23 февраля !",
                    },
                },
                {
                    8: { start: 0, duration: 24, compliments: "С 8 марта !" },
                },
                {
                    12: {
                        start: 0,
                        duration: 24,
                        compliments: "С днём космонавтики !",
                    },
                },
                {
                    1: { start: 0, duration: 24, compliments: "С 1 мая !" },
                    2: [
            // Если праздников несколько, то в массив
            // Строка class="***" должна задаваться в ", а не в '
                        {
                            start: 0,
                            duration: 24,
                            compliments:
                                '<span class="birthday">С ДНЮХОЙ !</span>',
                        },
                        {
                            start: 0,
                            duration: 24,
                            compliments:
                                '<span class="holiday">С 2 мая !</span>',
                        },
                    ],
                    9: { start: 0, duration: 24, compliments: "С 9 мая !" },
                },
                {
                    1: {
                        start: 0,
                        duration: 24,
                        compliments: "С 1 июня, Всемирным днём родителей !",
                    },
                },
                {
                    3: {
                        start: 0,
                        duration: 24,
                        compliments:
                            "3 июля, день независимости Республики Беларусь !",
                    },
                },
                {
                },
                {
                },
                {
                },
                {
                },
                {
                },
            ];
            
// =================== Добавил
	addHolyday(4, 0, 1,    // первое воскресенье мая
	{       
	start: 0,
	duration: 24,
	compliments: '<span class="holiday">именины Виктор</span>',
	});
	addHolyday(4, 0, -5,    // первое воскресенье мая
	{       
	start: 0,
	duration: 24,
	compliments: '<span class="holiday">именины Иван</span>',
	}
	);
		
// ===================             
// Вычисляет число соответствующее дню недели в месяце
// month - месяц (0-11)
// wday - день недели 0 - воскр, 1 - понед ....
// index 1 первый день, 2 - второй ... -1 - последний, -2 предпоследний
            function dayNWeek (month, wday, index)  {
				const wday1 = new Date(new Date().getFullYear(), month).getDay()
				const dd = wday - wday1
				let dayw = 1 + (dd >= 0? dd : 7 + dd);
				const dtwday = new Date(new Date().getFullYear(), month, dayw)
				const adayw =[]
				while (new Date(new Date().getFullYear(), month, dayw).getMonth() == month) {
					adayw.push(dayw)
					dayw += 7
				}
				return adayw[(index>0)? index-1 : adayw.length + index]
			}
			// добавляет праздник в массив holidays
			function addHolyday (month, wday, index, hobj) {
			const dt = dayNWeek (month, wday, index);
			if (holidays[month][dt]) {
			if (!Array.isArray(holidays[month][dt])) 
			holidays[month][dt] = [holidays[month][dt]];
			} else {
			holidays[month][dt] = [];
			}
			holidays[month][dt].push(hobj);
			}
// ========================================			
            function catholicDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var k = Math.floor(year / 100);
                var p = Math.floor((13 + 8 * k) / 25);
                var q = Math.floor(k / 4);
                var m = (15 - p + k - q) % 30;
                var n = (4 + k - q) % 7;
                var d = (19 * a + m) % 30;
                var e = (2 * b + 4 * c + 6 * d + n) % 7;
                if (d === 29 && e === 6) return new Date(year, 3, 19);
                if (d === 28 && e === 6 && (11 * m + 11) % 30 < 19)
                    return new Date(year, 3, 18);
                if (d + e > 9) return new Date(year, 3, d + e - 9);
                else return new Date(year, 2, 22 + d + e);
            }
  
            function orthodoxDate(year) {
                var a = year % 19;
                var b = year % 4;
                var c = year % 7;
                var d = (19 * a + 15) % 30;
                var e = (2 * b + 4 * c + 6 * d + 6) % 7;
                var f = d + e;
                return f <= 26
                    ? new Date(year, 3, 4 + f)
                    : new Date(year, 4, f - 26);
            }
  
//            const today = new Date("2 May 2021 07:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )
const today = new Date (2021, 4, 2)  // ======== для теста 2 мая 2021г. пасха, с 2 мая, с днюхой, именины Виктор, именины Иван ======
  
            function getActualCompliments(now) {
                const result = [];
                holidays.forEach((vm, month) => {
                    for (const day in vm) {
                        let hlds = vm[day];
                        if (!Array.isArray(hlds)) hlds = [hlds];
                        for (const hld of hlds) {
                            const currentDate = new Date(
                                now.getFullYear(),
                                month,
                                +day,
                                +hld.start
                            );
                            const rg = now.getTime() - currentDate.getTime();
                            if (0 <= rg && rg < hld.duration * 3600000) {
                                result.push(hld.compliments);
                            }
                        }
                    }
                });
  
                const caholic = catholicDate(now.getFullYear());
                const ortodox = orthodoxDate(now.getFullYear());
  
                if (
                    caholic.getMonth() == now.getMonth() &&
                    caholic.getDate() == now.getDate()
                )
                    result.push("С католической пасхой!");
  
                if (
                    ortodox.getMonth() == now.getMonth() &&
                    ortodox.getDate() == now.getDate()
                )
                    result.push('<span class="public_holiday">С православной пасхой!</span>');
  
                const radunitsa = new Date(ortodox);
                radunitsa.setDate(radunitsa.getDate() + 9);
                if (
                    radunitsa.getMonth() == now.getMonth() &&
                    radunitsa.getDate() == now.getDate()
                )
                    result.push("С радуницей !");
  
                const trinity = new Date(ortodox);
                trinity.setDate(trinity.getDate() + 49);
                if (
                    trinity.getMonth() == now.getMonth() &&
                    trinity.getDate() == now.getDate()
                )
                    result.push("С троицей!");
  
                return result;
            }
  
            const actualCompliments = getActualCompliments(today);
  
            console.log(actualCompliments);
  
            if (actualCompliments.length > 0) {
                const hollyday = document.getElementById("holiday");
                hollyday.style.display = "block";
                for (const cl of ["public_holiday", "holiday", "birthday"]) {
                    for (const c of actualCompliments) {
                        if (c.indexOf('class="' + cl + '"')>=0) {
                            const div = document.createElement("div");
                            hollyday.appendChild(div);
                            div.innerHTML = c;
                        }
                    }
                }
            }
        </script>
        <div id="footer"></div>
    </body>
</html>


всё работает, благодарю от души... :thanks:

Блондинка 23.12.2021 13:23

voraa,
а не подскажешь как можно исправить точность 'start' и 'duration', чтобы эти параметры задавать не часах, а с точность до минут, секунд...

{
start: 0:00:05,
duration: 23:50:45,
compliments: '<span class="holiday">С 2 мая !</span>',
}


возможно ли что нибудь типа такого сделать?

Блондинка 24.12.2021 22:45

народ, а не подскажете как можно исправить точность 'start' и 'duration', чтобы эти параметры задавать не в часах, а с точность до минут, секунд...

{
start: 0:00:05, // 0ч 00мин 05сек например
duration: 23:50:45, // 23ч 50мин 45сек например
compliments: '<span class="holiday">С 2 мая !</span>',
}


возможно ли что нибудь типа такого сделать?

voraa 25.12.2021 07:56

Строки 198-206 так
holidays.forEach((vm, month) => {
                    for (const day in vm) {
                        let hlds = vm[day];
                        if (!Array.isArray(hlds)) hlds = [hlds];
                        for (const hld of hlds) {
							const [sth, stm=0, sts=0] = (''+hld.start).split(':')
							const [drh, drm=0, drs=0] = (''+hld.duration).split(':')
                            const start = new Date(
                                now.getFullYear(),
                                month,
                                +day,
                                +sth, +stm, +sts
                            ).getTime();
                            const nt = now.getTime()
                            const end = start + ((drh*60+(+drm))*60 +(+drs))*1000;
                            if (start <= nt && nt < end) {
                                result.push(hld.compliments);
                            }
                        }
                    }
                });


start и duration задавать либо числом часов (0, 24 ...)
либо строкой ("7:00", "12:44:56" ...)

Блондинка 23.03.2022 21:52

Цитата:

Сообщение от voraa
start и duration задавать либо числом часов (0, 24 ...)
либо строкой ("7:00", "12:44:56" ...)

при попытке задать строкой, пропадают плавающие события, в религиозных праздниках не пробовала задавать строкой начало и продолжительность события...

https://ru.stackoverflow.com/questio...82%d0%b8%d1%8f


sorry, для теста установила пару событий на 24 апр(дата пасхи текущего года), всё заработало, значит причина была в том, что тестовая дата была за 21г.........

Блондинка 01.05.2022 06:33

народ, возможно ли выяснить сколько панов отображается в диве, и если больше одного, добавить стили к спанам ?
.public_holiday,
            .holiday,
            .birthday {
              border: 1px solid hsl(0, 0%, 50%);
              margin: 5px;
            }

ksa 03.05.2022 10:10

Сейчас многое можно реализовать, с точки зрения дочерних элементов...
<style>
p:not(:only-of-type) {
	color: red;
}
</style>
<div>
	<p>Item 1 - 1</p>
</div>
<div>
	<p>Item 2 - 1</p>
	<p>Item 2 - 2</p>
	<p>Item 2 - 3</p>
</div>

https://habr.com/ru/post/252181/

Блондинка 03.05.2022 21:18

ksa,
thank you very much, упустила из вида (забыла про)
:not


Часовой пояс GMT +3, время: 01:53.