Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   исправить и оптимизировать скрипт (https://javascript.ru/forum/misc/83179-ispravit-i-optimizirovat-skript.html)

Блондинка 07.10.2021 21:56

исправить и оптимизировать скрипт
 
есть такой скрипт
<!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <style>
    body { margin: 0; padding: 0; }
    #holiday {
        display: none;
        background: hsl(0,0%,90%);
        color: hsl(340,100%,50%);
        font: bold 24px/20px serif;
        text-align: center;
        padding: 15px 20px;
        border: 1px solid hsl(0,0%,50%);
        border-radius: 12px/9px;
    }
    </style>
    </head>
    <body>
        <div id="header">
        <div id="logo"></div>
        <div id="block_time-data"></div>
        </div>
        <div id="holiday">
        </div>
    <script type="text/javascript">
    var holidays = [
        
        { // January Январь
            '1': {'start': 0, 'duration': 24, 'compliments': 'С новым годом !'},
            '7': {'start': 0, 'duration': 24, 'compliments': 'С рождеством !'} },
        
        { // February Февраль
            '23': {'start': 0, 'duration': 24, 'compliments': 'С 23 февраля !'} },
        
        { // March Март
            '8': {'start': 0, 'duration': 12, 'compliments': 'С 8 марта !'} },
        
        { // April Апрель
            '12': {'start': 0, 'duration': 12, 'compliments': 'С днём космонавтики !'} },
        
        { // May Май
            '1': {'start': 0, 'duration': 24, 'compliments': 'С 1 мая !'},
            '2': {'start': 0, 'duration': 24, 'compliments': 'Петя, с ДНЮХОЙ !'},
            '9': {'start': 0, 'duration': 24, 'compliments': 'С 9 мая !'} },
        
        { // June Июнь
            '1': {'start': 0, 'duration': 24, 'compliments': 'С 1 июня, Всемирным днём родителей !'} },
        
        { // July Июль
        
            '3': {'start': 0, 'duration': 24, 'compliments': '3 июля, день независимости Республики Беларусь !'} },
        
        { // August Август
        
            '12': {'start': 0, 'duration': 24, 'compliments': '12 августа международный день молодёжи !'} },
        
        { // September Сентябрь
            '1': {'start': 0, 'duration': 24, 'compliments': '1 сентября, день знаний !'} },
        
        { // October Октябрь
            '1': {'start': 0, 'duration': 24, 'compliments': '1 октября, международный день пожилых людей !'} },
        
        { // November Ноябрь
            '7': {'start': 0, 'duration': 24, 'compliments': '7 ноября, день октябрьской революции !'} },
            
        { // December Декабрь
            '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);
    }
    
    function getActualCompliments()
    {
    var now = new Date("2 May 2021"); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000"
    var result = holidays.filter(v =>
    {
    var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);
    var durms = v.duration * 3600000;
    console.log(now, currentDate, (now - currentDate) / 3600000);
    var rg = now - currentDate;
    return rg <= durms && rg >= 0;
    }).map(v => v.compliments);
    var caholic = catholicDate(now.getFullYear());
    var 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("С православной пасхой!");
    
    var radunitsa = new Date(ortodox);
    radunitsa.setDate(radunitsa.getDate() + 9);
    if (radunitsa.getMonth() == now.getMonth() && radunitsa.getDate() == now.getDate())
    result.push("С радуницей !");
    
    var trinity = new Date(ortodox);
    trinity.setDate(trinity.getDate() + 49);
    if (trinity.getMonth() == now.getMonth() && trinity.getDate() == now.getDate())
    result.push("С троицей!");
    return result;
    }
    
    var actualCompliments = getActualCompliments();
    console.log(actualCompliments);
    if (actualCompliments.length > 0)
    {
    var hollyday = document.getElementById("holiday");
    hollyday.style.display = "block";
    for (var c of actualCompliments)
    {
    var div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
    }
    }
    function foo(month, day, compliment, hour = 0)
    {
    return { month: month, day: day, hour: hour, compliment: compliment }
    }
    
    var now9 = new Date();
    now9.setDate(now9.getDate() + 9);
    console.log(now9);
    
    var now49 = new Date();
    now49.setDate(now49.getDate() + 49);
    console.log(now49);
    
        d = new Date( "2 May 2021"); // d = new Date( "9 May 2021 00:00:00:001" )
    
    if((m = holidays[d.getMonth()]) && m[d.getDate()]) {
                m = m[d.getDate()];
        if(d.getHours()>=m.start) {
        var b = document.getElementById("holiday");
        if (!b) {
        b = document.createElement("div");
        b.id = "holiday";
        document.querySelector("body").appendChild(b);
        }
        b.innerHTML = m.compliments;
        b.style.display = "block";
        }  
    }
    </script>
    <div id="footer"></div>
    </body>
    </html>


1.) почему не отображается поздравление с пасхой, если в 108 строке указана дата 2.05.2021 ?

2.) как сделать чтобы массив с месяцами шёл не по порядку? (например в октябре нет праздников, и октябрь надо удалить из массива, или другими словами присвоить месяцам порядковый номер 1-12...)

Блондинка 10.10.2021 20:48

почему не отображается поздравление с пасхой, если в 108 строке указана дата 2.05.2021 ?

voraa 11.10.2021 08:19

Разберитесь в строках 167-175.
Что то вы не туда добавляете и затираете предыдущее поздравление (с пасхой)

Если заменить эти строки на
var h = document.getElementById("holiday");
 //       if (!b) {
        b = document.createElement("div");
//        b.id = "holiday";
        b.innerHTML = m.compliments;
        b.style.display = "block";
        h.appendChild(b);
 //       }

То появляются оба поздравления.

Блондинка 11.10.2021 14:46

<!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': {'start': 0, 'duration': 24, 'compliments': '<span class="birthday">С ДНЮХОЙ !</span>'},
           '2': {'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);
   }
   
   function getActualCompliments()
   {
   var now = new Date( "2 May 2021 00:00:00:001" ); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000"
   var result = holidays.filter(v =>
   {
   var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);
   var durms = v.duration * 3600000;
   console.log(now, currentDate, (now - currentDate) / 3600000);
   var rg = now - currentDate;
   return rg <= durms && rg >= 0;
   }).map(v => v.compliments);
   var caholic = catholicDate(now.getFullYear());
   var 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("С православной пасхой!");
   
   var radunitsa = new Date(ortodox);
   radunitsa.setDate(radunitsa.getDate() + 9);
   if (radunitsa.getMonth() == now.getMonth() && radunitsa.getDate() == now.getDate())
   result.push("С радуницей !");
   
   var trinity = new Date(ortodox);
   trinity.setDate(trinity.getDate() + 49);
   if (trinity.getMonth() == now.getMonth() && trinity.getDate() == now.getDate())
   result.push("С троицей!");
   return result;
   }
   
   var actualCompliments = getActualCompliments();
   console.log(actualCompliments);
   if (actualCompliments.length > 0)
   {
   var hollyday = document.getElementById("holiday");
   hollyday.style.display = "block";
   for (var c of actualCompliments)
   {
   var div = document.createElement("div");
   hollyday.appendChild(div);
   div.innerHTML = c;
   }
   }
   function foo(month, day, compliment, hour = 0)
   {
   return { month: month, day: day, hour: hour, compliment: compliment }
   }
   
   var now9 = new Date();
   now9.setDate(now9.getDate() + 9);
   console.log(now9);
   
   var now49 = new Date();
   now49.setDate(now49.getDate() + 49);
   console.log(now49);
   
       d = new Date( "2 May 2021 00:00:00:001" ); // d = new Date( "9 May 2021 00:00:00:001" )
   
   if((m = holidays[d.getMonth()]) && m[d.getDate()]) {
               m = m[d.getDate()];
       if(d.getHours()>=m.start) {
       
       var h = document.getElementById("holiday");
        //       if (!b) {
       b = document.createElement("div");
       b.id = "holiday";
       b.innerHTML = m.compliments;
       b.style.display = "block";
       h.appendChild(b);
       }
       
   }
   </script>
   <div id="footer"></div>
   </body>
   </html>


Так есть два поздравления, а третье (строка 50) где-то потерялось...

и как сделать чтобы все три поздравления были в отдельных спанах, внутри дива, с соответствующими классами? другими словами присвоить поздравлению с пасхой, класс госпраздника (public_holiday) ?

voraa 11.10.2021 16:19

Я не совсем понимаю, что и как там должно работать?
Что такое
var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);

В v нет таких полей.

Блондинка 18.10.2021 00:08

<!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': {'start': 0, 'duration': 24, 'compliments': '<span class="birthday">С ДНЮХОЙ !</span>'},
           '2': {'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);
   }
   
   function getActualCompliments()
   {
   var now = new Date( "2 May 2021 00:00:00:001" ); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000"
   var result = holidays.filter(v =>
   {
   var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);
   var durms = v.duration * 3600000;
   console.log(now, currentDate, (now - currentDate) / 3600000);
   var rg = now - currentDate;
   return rg <= durms && rg >= 0;
   }).map(v => v.compliments);
   var caholic = catholicDate(now.getFullYear());
   var 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>");
   
   var radunitsa = new Date(ortodox);
   radunitsa.setDate(radunitsa.getDate() + 9);
   if (radunitsa.getMonth() == now.getMonth() && radunitsa.getDate() == now.getDate())
   result.push("С радуницей !");
   
   var trinity = new Date(ortodox);
   trinity.setDate(trinity.getDate() + 49);
   if (trinity.getMonth() == now.getMonth() && trinity.getDate() == now.getDate())
   result.push("С троицей!");
   return result;
   }
   
   var actualCompliments = getActualCompliments();
   console.log(actualCompliments);
   if (actualCompliments.length > 0)
   {
   var hollyday = document.getElementById("holiday");
   hollyday.style.display = "block";
   for (var c of actualCompliments)
   {
   var div = document.createElement("div");
   hollyday.appendChild(div);
   div.innerHTML = c;
   }
   }
   function foo(month, day, compliment, hour = 0)
   {
   return { month: month, day: day, hour: hour, compliment: compliment }
   }
   
   var now9 = new Date();
   now9.setDate(now9.getDate() + 9);
   console.log(now9);
   
   var now49 = new Date();
   now49.setDate(now49.getDate() + 49);
   console.log(now49);
   
       d = new Date( "2 May 2021 00:00:00:001" ); // d = new Date( "9 May 2021 00:00:00:001" )
   
   if((m = holidays[d.getMonth()]) && m[d.getDate()]) {
               m = m[d.getDate()];
       if(d.getHours()>=m.start) {
       
       var h = document.getElementById("holiday");
        //       if (!b) {
       b = document.createElement("div");
       b.id = "holiday";
       b.innerHTML = m.compliments;
       b.style.display = "block";
       h.appendChild(b);
       }
       
   }
   </script>
   <div id="footer"></div>
   </body>
   </html>


как исправить строки 38-67, чтобы поздравление с днюхой не затиралось поздравлением с 2 мая, чтобы на странице были все три поздравления и с пасхой, и с 2 мая и с днюхой?

voraa 18.10.2021 17:02

Зачем вы поставили console.log в строке 110?
А если поставили, то почему не смотрите, что там выдается?

(Если уж взялись писать программы, так учитесь.
Подсказать можно, но писать за вас влом.)

voraa 18.10.2021 17:18

111 var rg = now - currentDate;

Где вы та лихо научились даты вычитать?

рони 18.10.2021 17:35

Цитата:

Сообщение от voraa
Где вы та лихо научились даты вычитать?

:) что-то не так?

Блондинка 18.10.2021 22:48

Цитата:

Сообщение от voraa (Сообщение 540772)
(Если уж взялись писать программы, так учитесь.
Подсказать можно, но писать за вас влом.)

так подскажите по конкретным строкам, 49-51, как их исправить чтобы поздравление с 2 мая не затирало поздравление с днюхой...

voraa 19.10.2021 08:10

Цитата:

Сообщение от Блондинка
так подскажите по конкретным строкам, 49-51

Причем тут эти строки. Только эти строки не исправить, что бы работало.

Вы так и не ответили на мои простые вопросы

Цитата:

Сообщение от voraa
Зачем вы поставили console.log в строке 110?
А если поставили, то почему не смотрите, что там выдается?

Цитата:

Сообщение от voraa
Что такое
var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);

<!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: { start: 0, duration: 24,  compliments: [
                              '<span class="birthday">С ДНЮХОЙ !</span>',
                              '<span class="holiday">С 2 мая !</span>',
                           ],  },
    //           '2': {'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 00:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )

function getActualCompliments(now) {
  //   var now = new Date( "2 May 2021 00:00:00:001" ); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000"

  /*
var result = holidays.filter(v =>
{
var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);
var durms = v.duration * 3600000;
console.log(now, currentDate, (now - currentDate) / 3600000);
var rg = now - currentDate;
return rg <= durms && rg >= 0;
}).map(v => v.compliments);
*/

  const result = [];
  holidays.forEach((vm, month) => {
    for (const day in vm) {
      const hld = vm[day];
      const currentDate = new Date(now.getFullYear(), month, +day, +hld.start);
      const rg = now.getTime() - currentDate.getTime();
      if (0 <= rg && rg < hld.duration * 3600000) {
        let compl = hld.compliments;
        if (!Array.isArray(compl)) compl = [compl];
        result.push(...compl);
      }
    }
  });

  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 (var c of actualCompliments) {
    const div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
  }
}

/* Что ниже, я не понимаю
function foo(month, day, compliment, hour = 0) {
  return { month: month, day: day, hour: hour, compliment: compliment };
}

var now9 = new Date();
now9.setDate(now9.getDate() + 9);
console.log(now9);

var now49 = new Date();
now49.setDate(now49.getDate() + 49);
console.log(now49);

if ((m = holidays[d.getMonth()]) && m[d.getDate()]) {
  m = m[d.getDate()];
  if (d.getHours() >= m.start) {
    var h = document.getElementById("holiday");
    //       if (!b) {
    b = document.createElement("div");
    b.id = "holiday";
    b.innerHTML = m.compliments;
    b.style.display = "block";
    h.appendChild(b);
  }
}
*/
    </script>
    <div id="footer"></div>
  </body>
</html>

Блондинка 19.10.2021 20:40

Цитата:

Сообщение от voraa (Сообщение 540791)
Вы так и не ответили на мои простые вопросы

если бы блондинка знала бы ответы на эти вопросы...
но судя по всему строки 179-185, это расчёт дат радуницы (+9 дней) и троицы (+49 дней к пасхе) .........

Блондинка 20.10.2021 09:36

voraa,
спс, всё вроде бы работает, но возникают вопросы,

1.) а что делать если вдруг старт и/или продолжительность у событий разная...

2.) а как правильно сделать, если вдруг в одном месяце из двенадцати, нет событий(праздников)...

3.) возможно ли отсортировать все события за день, чтобы сначала шли спаны с классом 'public_holiday', вторыми с классом 'holiday', и последними с классом 'birthday' ?

voraa 20.10.2021 16:24

Цитата:

Сообщение от Блондинка
1.) а что делать если вдруг старт и/или продолжительность у событий разная...

Ну тогда наверно надо поменять формат описания праздников. Допустить массив не в compliments, а в самом дне. Типа так
2: [ { start: 6, duration: 24*7-6,  compliments:  '<span class="birthday">С ДНЮХОЙ !</span>'},
       { start: 0, duration: 24,  compliments: '<span class="holiday">С 2 мая !</span>'}
         ],

Ну и программу тогда тоже подправить
Цитата:

Сообщение от Блондинка
2.) а как правильно сделать, если вдруг в одном месяце из двенадцати, нет событий(праздников)...

Писать пустой объект для этого месяца, без дней. Просто {}

Цитата:

Сообщение от Блондинка
3.) возможно ли отсортировать все события за день, чтобы сначала шли спаны с классом 'public_holiday', вторыми с классом 'holiday', и последними с классом 'birthday' ?

Можно. Только все тексты поздравлений в compliments должны иметь вид <span class="класс"> Текст </span>

Тогда строки 167-171 так

for (const cl of ['public_holiday', 'holiday', 'birthday']) {
  for (var c of actualCompliments) {
    if (c.indexof('class="'+cl+'"') {
    const div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
  }
  }
}

Блондинка 20.10.2021 16:55

Цитата:

Сообщение от voraa
Писать пустой объект для этого месяца, без дней. Просто {}

а возможно ли просто указать порядковый номер месяца, и просто пропускать ненужные месяцы? типа как в самой простой версии скрипта

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.holiday {
    text-align: center;
}
</style>
</head>
<body>
<script>
var holidays = {
    '5': {
        '2':
        {'start': 0, 'duration': 24, 'compliments': 'С 2 мая'},
        '2':
        {'start': 0, 'duration': 24, 'compliments': 'С днюхой!'}  
    }
}, d = new Date( "2 May 2021"), m;

if((m = holidays[d.getMonth()+1]) && m[d.getDate()]) {
    m = m[d.getDate()];
    if(d.getHours()>=m.start) {
        var b = document.createElement('div');
        b.className = 'holiday';
        b.innerHTML = m.compliments;
        document.querySelector('body').appendChild(b)
    }  
}
</script>
</body>
</html>

Блондинка 20.10.2021 17:01

Цитата:

Сообщение от voraa
Можно. Только все тексты поздравлений в compliments должны иметь вид <span class="класс"> Текст </span>

ну это само собой разумеется, даже если текста поздравления нету, а просто адрес картинки, один хер тег имг надо будет заключать в <span class="класс"> <img.......> </span>

Блондинка 20.10.2021 18:07

Цитата:

Сообщение от voraa
Можно. Только все тексты поздравлений в compliments должны иметь вид <span class="класс"> Текст </span>

Тогда строки 167-171 так

for (const cl of ['public_holiday', 'holiday', 'birthday']) {
  for (var c of actualCompliments) {
    if (c.indexof('class="'+cl+'"') {
    const div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
  }
  }
}

блин, ниХфига не получается

<!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: { start: 0, duration: 24,  compliments: [
                              '<span class="birthday">С ДНЮХОЙ !</span>',
                              '<span class="holiday">С 2 мая !</span>',
                           ],  },
    //           '2': {'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 00:00:00:001"); // d = new Date( "9 May 2021 00:00:00:001" )

function getActualCompliments(now) {
  //   var now = new Date( "2 May 2021 00:00:00:001" ); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000"

  /*
var result = holidays.filter(v =>
{
var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour);
var durms = v.duration * 3600000;
console.log(now, currentDate, (now - currentDate) / 3600000);
var rg = now - currentDate;
return rg <= durms && rg >= 0;
}).map(v => v.compliments);
*/

  const result = [];
  holidays.forEach((vm, month) => {
    for (const day in vm) {
      const hld = vm[day];
      const currentDate = new Date(now.getFullYear(), month, +day, +hld.start);
      const rg = now.getTime() - currentDate.getTime();
      if (0 <= rg && rg < hld.duration * 3600000) {
        let compl = hld.compliments;
        if (!Array.isArray(compl)) compl = [compl];
        result.push(...compl);
      }
    }
  });

  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 (var c of actualCompliments) {
  if (c.indexof('class="'+cl+'"') {
  const div = document.createElement("div");
  hollyday.appendChild(div);
  div.innerHTML = c;
  }
  }
  }
    </script>
    <div id="footer"></div>
  </body>
</html>


хз, что не так...

Блондинка 20.10.2021 20:08

Цитата:

Сообщение от voraa
Ну тогда наверно надо поменять формат описания праздников. Допустить массив не в compliments, а в самом дне. Типа так
2: [ { start: 6, duration: 24*7-6,  compliments:  '<span class="birthday">С ДНЮХОЙ !</span>'},
       { start: 0, duration: 24,  compliments: '<span class="holiday">С 2 мая !</span>'}
         ],

Ну и программу тогда тоже подправить

а что именно подправить? пробую заменить и только поздравление с пасхой вижу...

<!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: [ { 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 00: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) {
      const hld = vm[day];
      const currentDate = new Date(now.getFullYear(), month, +day, +hld.start);
      const rg = now.getTime() - currentDate.getTime();
      if (0 <= rg && rg < hld.duration * 3600000) {
        let compl = hld.compliments;
        if (!Array.isArray(compl)) compl = [compl];
        result.push(...compl);
      }
    }
  });

  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 (var c of actualCompliments) {
    const div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
  }
}


    </script>
    <div id="footer"></div>
  </body>
</html>

Блондинка 21.10.2021 22:38

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

Спасайте, помогите кто чем может...

voraa 22.10.2021 07:15

<!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: [ { 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 (var c of actualCompliments) {
    const div = document.createElement("div");
    hollyday.appendChild(div);
    div.innerHTML = c;
  }
}
 
 
    </script>
    <div id="footer"></div>
  </body>
</html>

voraa 22.10.2021 07:21

Цитата:

Сообщение от Блондинка
второй день трахаюсь с этим скриптом,

А на хрена вы это делаете? Вас кто то заставляет?
Я вот никогда не возьмусь, например, чинить автомобиль или штукатурить стены. От этого только хуже станет. Потому, что не умею и учиться не хочу.

Блондинка 22.10.2021 21:53

Цитата:

Сообщение от voraa
А на хрена вы это делаете? Вас кто то заставляет?

просто хочу сделать сайт про кактусы, и на данный момент почти всё готово из скриптов, не хватает только двух, этого скрипта поздравлений, и календаря...

Блондинка 24.10.2021 09:22

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

voraa 24.10.2021 12:36

Я написал массив для 2 мая и написал, как сделать сортировку
<!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(
          // Строка class="***" должна задаваться в ", а не в '
						'<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;
						}
					}
				}
				/*				for (var c of actualCompliments) {
								const div = document.createElement("div");
								hollyday.appendChild(div);
								div.innerHTML = c;
							}*/
			}
		</script>
		<div id="footer"></div>
	</body>
</html>

Блондинка 24.10.2021 17:31

voraa,
вот сейчас всё работает на отлично, благодарю...

Блондинка 31.10.2021 18:55

народ, в году есть несколько событий (праздников) которые отмечают не конкретного числа, а в определённый день недели конкретного месяца, например третий вторник октября, или второй понедельник апреля и тд

или отсчёт может идти с конца месяца, например последняя суббота сентября, или предпоследняя пятница февраля, (в месяце ведь может быть и 4 и 5 дней недели)

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

посоветовали что-то типа такого добавить...

const holiday = {
  month: 6, //месяц праздника
  day: 7, //номер дня недели
  number: -1 // номер недели — отрицательный индекс означает что счёт ведётся с конца
};
//День Военно-морского флота
function getDate(date, year) {
  const d = new Date();
  d.setFullYear(year);
  d.setMonth(holiday.month, 1);
  const firstDay =
    1 + holiday.day + (d.getDay() < holiday.day ? -d.getDay() : 7 - d.getDay());
  const days = [firstDay];
  let day = firstDay;
  while (
    new Date(year, holiday.month, (day += 7)).getMonth() == holiday.month
  ) {
    days.push(day);
  }
  const index = (holiday.number < 0 ? days.length : 0) + holiday.number;
  //return days[index];
  return new Date(year, holiday.month, days[index]).toLocaleString();
}
console.log(getDate(holiday, 2022));


народ, помогите добавить несколько подобных событий в этот скрипт...

Блондинка 01.11.2021 20:55

никто не знает?


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