Affichage des articles dont le libellé est Digital Clock. Afficher tous les articles
Affichage des articles dont le libellé est Digital Clock. Afficher tous les articles

JavaScript Real Time Analog Clock

How to Create an Analog with HTML, CSS and  JavaScript


How to Create an Analog with HTML, CSS and  JavaScript

In this Javascript Tutorial, we will see how to create an Analog clock with an integrated digital time display.



Project Source Code:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Analog Clock</title>
<style>

/* Import the Poppins font from Google Fonts */
@import url(
'https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap'
);

body
{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: 'Poppins', sans-serif;
background: linear-gradient(45deg, #16213e, #1a1a2e);
}

.clock-container{ position: relative; }

canvas
{
background: linear-gradient(45deg, #16213e, #1a1a2e);
border-radius: 50%;
box-shadow: 0 0 0 10px rgba(255,255,255,0.1),
0 0 20px rgba(0,0,0,0.3),
inset 0 0 50px rgba(0, 0, 0, 0.3);
}

.digital-time
{
position: absolute;
bottom: 20%;
left: 50%;
transform: translateX(-50%);
font-size: 1.5em;
color: #e94560;
text-transform: 0 0 10px rgba(233,69,96,0.5);
}


</style>
</head>
<body>

<div class="clock-container">

<canvas id="clock" width="400" height="400"></canvas>
<div class="digital-time" id="digital-time">00:00:00</div>

</div>

<script>
// Get the canvas element and its drawing context
const canvas = document.getElementById('clock');
const ctx = canvas.getContext('2d');
// Calculate the radius of the clock
const radius = canvas.height / 2;
// Move the origin of the canvas to the center
ctx.translate(radius, radius);

function drawClock(){

drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
updateDigitalTime();

}


// Function to draw the clock face
function drawFace(ctx, radius){
// Create a radial gradient for the clock face
const grad = ctx.createRadialGradient(0,0,radius * 0.95, 0, 0, radius*1.05);
grad.addColorStop(0, '#16213e'); // Inner color
grad.addColorStop(0.5, '#1a1a2e'); // Middle color
grad.addColorStop(1, '#16213e'); // Outer color

// Draw the clock face circle
ctx.beginPath();
ctx.arc(0,0,radius, 0, 2 * Math.PI);
ctx.fillStyle = grad;
ctx.fill();

// Draw the center circle
ctx.beginPath();
ctx.arc(0,0,radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#e94560';
ctx.fill();

}

// Function to draw the numbers and ticks on the clock
function drawNumbers(ctx, radius){
// Set font size and alignment
ctx.font = radius * 0.15 + "px Poppins";
ctx.textBaseLine = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#fff"; // White color for numbers

// Draw numbers 1 through 12
for(let num = 1; num <= 12; num++){
let ang = num * Math.PI / 6; // Calculate angle for each number
ctx.rotate(ang); // Rotate canvas
ctx.translate(0, -radius * 0.82); // Move canvas to position
ctx.rotate(-ang); // Rotate canvas back
ctx.fillText(num.toString(), 0, 0); // Draw number
ctx.rotate(ang); // Rotate canvas back
ctx.translate(0, radius * 0.82); // Move canvas back
ctx.rotate(-ang); // Rotate canvas back
}

// Draw ticks for each minute
for(let i = 0; i < 60; i++){
let ang = i * Math.PI / 30; // Calculate angle for each tick
ctx.beginPath();
ctx.rotate(ang);

if(i % 5 === 0){
// Draw long ticks for hours
ctx.moveTo(radius * 0.9, 0);
ctx.lineTo(radius * 0.95, 0);
ctx.strokeStyle = "#e94560";
ctx.lineWidth = radius * 0.02;
}
else
{
// Draw short ticks for minutes
ctx.moveTo(radius * 0.95, 0);
ctx.lineTo(radius * 0.97, 0);
ctx.strokeStyle = "#0f3460";
ctx.lineWidth = radius * 0.01;
}

ctx.stroke(); // Render the tick
ctx.rotate(-ang); // Rotate canvas back
}

}


// Function to draw the clock hands
function drawTime(ctx, radius){
const now = new Date(); // Get current time
let hour = now.getHours(); // Get hours
let minute = now.getMinutes(); // Get minutes
let second = now.getSeconds(); // Get seconds

hour = hour % 12; // Convert hour to 12-hour format
hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60))
+ (second * Math.PI / (360 * 60));
// Draw hour hand
drawHand(ctx, hour, radius * 0.5, radius * 0.07, '#fff');

minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
// Draw hour minute
drawHand(ctx, minute, radius * 0.75, radius * 0.05, 'yellow');

second = (second * Math.PI / 30);
// Draw hour second
drawHand(ctx, second, radius * 0.9, radius * 0.02, '#e94560');
}


// Function to draw a clock hand
function drawHand(ctx, pos, length, width, color){
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.shadowColor = color; // Shadow color
ctx.shadowBlur = 10; // Shadow blur
ctx.strokeStyle = color; // Hand color
ctx.moveTo(0,0); // Start from center
ctx.rotate(pos); // Rotate canvas
ctx.lineTo(0, -length); // Draw line
ctx.stroke(); // Render the hand
ctx.rotate(-pos); // Rotate canvas back
ctx.shadowBlur = 0; // Remove shadow
}


// Function to update the digital time display
function updateDigitalTime(){
const now = new Date();
const timeString = now.toLocaleTimeString('en-us',
{hour12:true, hour:'2-digit', minute:'2-digit'});
document.getElementById('digital-time').textContent = timeString;
}


// Call drawClock every second to update the clock
setInterval(drawClock, 1000);


</script>

</body>
</html>






OUTPUT:

JavaScript Real Time Analog Clock





Python Tkinter Digital Clock

How to Create Digital Clock In Python Tkinter

Digital Clock In Python Tkinter



In this Python tutorial we will create a digital clock using the Tkinter library for the graphical user interface. 
It continuously updates every second to display the current time in hours, minutes, and seconds.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:


import tkinter as tk
from time import strftime

def time():
# Get the current time in the specified format
string = strftime("%H:%M:%S %p")

# Update the label text with the current time
lbl.config(text = string)

# Schedule the time function to be called after 1000 milliseconds (1 second)
lbl.after(1000, time)


# Create the main Tkinter window
root = tk.Tk()
root.title("Digital Clock")

# Create a label for displaying the digital clock
lbl = tk.Label(root, font=('Helvatica', 40, 'bold'), background="#2f3640",
foreground="#fbc531")

# Pack the label to the center of the window
lbl.pack(anchor = 'center')

# Call the time function to start updating the clock
time()

root.mainloop()



The Final Result:

Python Tkinter Digital Clock









Java Digital Clock In Netbeans

How to Create Digital Clock in Java NetBeans

Java Digital Clock In Netbeans




In this Java Tutorial we will see How To Make a Digital Clock, With Hours, Minutes and Seconds In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create a JPanel named centerPanel with a visually appealing gradient background.
- Create a JLabel to display the current time.
- Update Timer continuously using a Timer that calls the updateClock method every second.





Project Source Code:


package new_tutorials;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;



public class Digital_Clock extends JFrame {

    private JLabel timeLabel;
    
    public Digital_Clock(){
    
        setTitle("Digital Clock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setResizable(false);

        
    // Create a JPanel with a background gradient    
    JPanel centerPanel = new JPanel(new GridBagLayout()){
    
        @Override
        protected void paintComponent(Graphics g){
            
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            
            // Define a gradient paint for the background
            GradientPaint gradient = new GradientPaint(new Point(0,0), new Color(37, 116, 169),
                                new Point(0,getHeight()), new Color(78, 154, 217) );
            
            g2d.setPaint(gradient);
            
            // Fill the panel with the gradient paint
            g2d.fillRect(0,0,getWidth(), getHeight());
            g2d.dispose();          
        }
    };
    add(centerPanel);
    
    timeLabel = new JLabel();
    timeLabel.setFont(new Font("Arial", Font.BOLD, 56));
    timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
    timeLabel.setForeground(Color.white);
    
    
     // Add timeLabel to the center panel with padding
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(30, 30, 30, 30);  // Padding
        
        centerPanel.add(timeLabel, gbc);
        
        // Start a timer to update the clock every second
        Timer timer = new Timer(1000, e->updateClock());
        timer.start();
        
        // Initial clock update
        updateClock();
    
    }
    
    private void updateClock(){
        
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String currentTime = sdf .format(new Date());
        timeLabel.setText(currentTime);
        
    }
    
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(()->{});
        
           Digital_Clock dc = new Digital_Clock();
           dc.setVisible(true);
        
    }
    
    
}


The Final Result:



Java Digital Clock




Javascript - Create a Digital Clock

How To Make a Digital Clock Using Javascript  


Create a Digital Clock in Javascript


In This Javascript Tutorial we will See How To build a digital clock using JavaScript. 
The clock updates automatically every second, providing an interactive and dynamic experience for the users. 
Feel free to customize the styling or integrate the clock into your own web projects. Remember to experiment with the code and explore additional features you can add to enhance the clock's functionality . 



Project Source Code:

    
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>

<style>
#clock{
display: block;
width: 40%;
margin: 10px auto;
padding: 10px;
background-color: #3c3c3c;
color: #fff;
font-size: 36px;
font-family: Arial, sans-serif;
text-align: center;
border-radius: 5px;
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
}

</style>


</head>
<body>

<div id="clock"></div>

<script>

function updateClock()
{
// get the current time
var currentTime = new Date();
// get the hours, minutes, and seconds from the
// current time
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// format the hours, minutes,
// and seconds to always display two digits
if(hours < 10) { hours = "0" + hours; }

if(minutes < 10) { minutes = "0" + minutes; }

if(seconds < 10) { seconds = "0" + seconds; }

// get the clock div
var clockDiv = document.getElementById("clock");

// update the clock div with the current time
clockDiv.innerHTML = hours + ":" + minutes + ":" + seconds;

}

// calls the updateClock() function every 1000 milliseconds
// (or 1 second)
setInterval(updateClock, 1000);

</script>

</body>
</html>





Code Explanation:

This JavaScript code consists of a function called updateClock(), which is responsible for fetching the current time, formatting it, and updating the clock display on the webpage. Let's break down the code to understand its functionality.

Fetching Current Time: The updateClock() function starts by creating a new Date object called currentTime, which holds the current date and time. 

Extracting Hours, Minutes, and Seconds: Next, the code extracts the hours, minutes, and seconds from the currentTime object using the getHours(), getMinutes(), and getSeconds() methods, respectively.

Formatting Time: To ensure that the hours, minutes, and seconds are always displayed with two digits, the code checks if any of them are less than 10. If so, a leading zero is added to the value using simple conditional statements. 

Updating the Clock Display: The code retrieves the clock element from the webpage using the getElementById() method and assigns it to the clockDiv variable. Then, it updates the innerHTML property of the clockDiv with the formatted time (hours, minutes, and seconds). 

Automatic Clock Update: To make the clock update every second, the code employs the setInterval() function. It calls the updateClock() function every 1000 milliseconds (1 second), ensuring that the displayed time is always accurate and up to date.




OUTPUT:



Digital Clock Using Javascript