Digital Clock in Go Programming Language

 

In this tutorial, we will learn how to create a digital clock that displays the current time using Go programming language. The objective is to build a simple yet functional clock that updates every second.

Objective

The objective of this project is to create a digital clock that will display the current time in hours, minutes, and seconds. The clock will continuously update itself every second and show the exact current time in a clean and easy-to-read format.

Code: Digital Clock in Go

package main

import (
    "fmt"
    "time"
)

func main() {
    for {
        // Get the current time
        currentTime := time.Now().Format("15:04:05")

        // Clear the screen
        fmt.Print("\033[H\033[2J")

        // Print the current time
        fmt.Println("Digital Clock")
        fmt.Println("Current Time:", currentTime)

        // Wait for 1 second
        time.Sleep(1 * time.Second)
    }
}

Explanation of the Program

Let’s break down the structure of this program:

  • Importing Packages: We import two packages: fmt for formatted I/O operations and time to handle time-related functions.
  • Infinite Loop: The for loop runs indefinitely, allowing the clock to update every second.
  • Getting the Current Time: time.Now().Format("15:04:05") is used to get the current time in the “HH:MM:SS” format. The Format method uses the 24-hour clock notation.
  • Clearing the Screen: The code fmt.Print("\033[H\033[2J") is used to clear the terminal screen every time before printing the updated time. This provides the effect of a dynamic updating clock.
  • Displaying the Time: We print the title “Digital Clock” and the current time on the screen.
  • Sleep Function: time.Sleep(1 * time.Second) pauses the execution for 1 second, allowing the time to update each second.

How to Run the Program

Follow these steps to run the Digital Clock program on your machine:

  1. Install Go programming language from Go Downloads.
  2. Create a new Go file named digital_clock.go and copy the code into this file.
  3. Open the terminal or command prompt and navigate to the folder where your digital_clock.go file is saved.
  4. Run the program using the following command:
    go run digital_clock.go
  5. You should now see a digital clock that updates every second, displaying the current time.
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *