LeetCampus
Interview Question

Write a code to display the current time?

July 24, 2025
0 views
Difficulty: Easy
Popularity: Common
Share on

Question Explanation

Displaying the current time is a fundamental task in programming that tests a candidate's understanding of date and time manipulation. Interviewers often ask this question to assess a candidate's familiarity with date/time libraries and their ability to implement basic functionality in their chosen programming language. Understanding how to work with time is crucial in various applications, from logging events to scheduling tasks. This question also serves as a gateway to discuss topics such as time zones, formatting, and localization, which are essential in global applications. Common misconceptions include assuming that time is always represented in a single format or that time zones are irrelevant. In reality, handling time correctly requires a solid grasp of how to manipulate date objects and format them for user interfaces. In practical applications, the ability to display the current time accurately can impact user experience significantly, especially in applications that rely on real-time data.

Sample Answers

Example 1: Using Python's datetime Module

To display the current time in Python, you can use the datetime module. Here’s a simple example:

from datetime import datetime

# Get the current time
current_time = datetime.now()

# Format the time
formatted_time = current_time.strftime('%H:%M:%S')
print('Current Time:', formatted_time)

Explanation:

  1. Importing the Module: We start by importing the datetime class from the datetime module.
  2. Getting Current Time: The now() method retrieves the current date and time.
  3. Formatting: We format the time using strftime(), where %H, %M, and %S represent hours, minutes, and seconds, respectively.
  4. Output: Finally, we print the formatted time.

This method is efficient and leverages built-in functionality to handle time formatting and retrieval.

Example 2: Display Time in JavaScript

In JavaScript, displaying the current time can be done easily using the Date object. Here’s how:

// Get the current date and time
const now = new Date();

// Extract hours, minutes, and seconds
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

// Format the time string
const currentTime = `${hours}:${minutes}:${seconds}`;
console.log('Current Time:', currentTime);

Explanation:

  1. Creating a Date Object: The Date constructor initializes a new date object with the current date and time.
  2. Extracting Components: We use getHours(), getMinutes(), and getSeconds() methods to retrieve the respective components.
  3. String Interpolation: We format the output into a string using template literals.
  4. Output: Finally, we log the formatted time to the console.

This approach is straightforward and captures the essence of real-time applications in JavaScript.

Example 3: Current Time in Java

In Java, you can utilize the LocalTime class from the java.time package introduced in Java 8 to display the current time. Here’s an example:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class CurrentTime {
    public static void main(String[] args) {
        // Get the current time
        LocalTime currentTime = LocalTime.now();
        
        // Format the time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern('HH:mm:ss');
        String formattedTime = currentTime.format(formatter);
        
        // Display the time
        System.out.println('Current Time: ' + formattedTime);
    }
}

Explanation:

  1. Importing Classes: We import the necessary LocalTime and DateTimeFormatter classes.
  2. Getting Current Time: LocalTime.now() fetches the current time without a date.
  3. Formatting: We create a DateTimeFormatter instance to specify the desired format.
  4. Output: Finally, we print the formatted time to the console.

This method is robust and adheres to best practices in modern Java programming.

Keywords

current timedate and time manipulationprogrammingtime zonesuser interface

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions