Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Print Current Date and Time

Displaying the current date and time is a common task in programming. Each programming language provides different ways to get and format the current date and time. Below are examples of how to achieve this in C, C++, Python, and Java.

(a.) C Code

#include <stdio.h>
#include <time.h>

int main() {
  time_t t;
  struct tm *tm_info;
  char buffer[26];

  time(&t);
  tm_info = localtime(&t);

  strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
  printf("Current Date and Time: %s
", buffer);

  return 0;
}
Output:-
Current Date and Time: 2024-01-01 12:34:56

(b.) C++ Code

#include <iostream>
#include <ctime>

int main() {
  time_t t = time(0);
  struct tm *now = localtime(&t);
  char buffer[80];
  strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", now);
  std::cout << "Current Date and Time: " << buffer << std::endl;
  return 0;
}
Output:-
Current Date and Time: 2024-01-01 12:34:56

(c.) Python Code

from datetime import datetime

now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Current Date and Time:", current_time)
Output:-
Current Date and Time: 2024-01-01 12:34:56

(d.) Java Code

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDateTime {
  public static void main(String[] args) {
      LocalDateTime now = LocalDateTime.now();
      DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      String currentTime = now.format(format);
      System.out.println("Current Date and Time: " + currentTime);
  }
}
Output:-
Current Date and Time: 2024-01-01 12:34:56