Menu Atas

Iklan

Friday, October 27, 2023, October 27, 2023 WIB
Last Updated 2023-10-28T05:38:16Z
codesHtmljavascript

how to create Digital Clock with JavaScript #WatuXTeam

Advertisement

 


HTML
    <div class="contener">
        <div class="date-time">
            <div class="img"></div>
            <div class="">
                <div class="day">
                    Tody is :
                    <span class="date"></span>
                    <span class="month"></span>
                    <span class="year"></span>
                </div>
                <div class="time">
                    Corrent time is :
                    <spam class="hours">00</spam> :
                    <spam class="minut">00</spam> :
                    <spam class="secound">00</spam>
                    <span class="formet">--</span>
                </div>
            </div>
        </div>
    </div>
CSS  CODE 
    .contener { display: flex; align-items: center; justify-content: center;}
    .date-time{ display: flex; align-items: center; width: max-content; padding: 10px 15px; border: 2px solid #333;font-family: system-ui; border-radius: 5px; } 
    .img{  display: block; margin-right: 20px; width: 50px; height: 50px; border-radius: 3px; background-size: cover;}
    .img.moon{background-image: url(./moon.jpg);}
    .img.sun{ background-image: url(./sun.jpg);}
    .day{ font-size: 24px; margin-bottom: 5px; font-weight: 500;}
    .time{ font-family: sans-serif;}
    .formet { font-weight: 600;}
  
SCRIPT CODE 
    function time() {
        setInterval(() => {
            var newDate = new Date();
            date = newDate.getDate(); month = newDate.getMonth(); year = newDate.getFullYear();
            hours = newDate.getHours(); minut = newDate.getMinutes(); second = newDate.getSeconds(); f = 'AM';
            monthString = ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'];
    
            var img = document.querySelector('.img');
            hours > 6 && hours < 18
                ? img.classList.add('sun')
                : img.classList.add('moon');
    
            if (hours == 0) { hours = 12;}
            if (hours > 12) { hours = hours - 12; f = 'PM'; }
    
            Number.prototype.num = function (e) {
                for (var n = this.toString(); n.length < e; n = 0 + n);
                return n;
            }
    
            element = ['date', 'month', 'year', 'hours', 'minut', 'secound', 'formet']
            value = [date.num(2), monthString[month], year, hours.num(2), minut.num(2), second.num(2), f];
    
            for (let i = 0; i < element.length; i++) {
                el = document.getElementsByClassName(element[i])[0].innerHTML = value[i];
            }
        }, 1000);
    }
    time();