Data and Time in C++

Working with Date and Time in C++ programming to get Computer's current date and time in different formats by using a standard Time 'time.h' library of C++ programming language.

Program Printing Computer Current Time

Program

#include<iostream.h>
#include<conio.h>
#include<time.h> //including Library for working with Time and Date.
void main()
{
time_t now;
  tm *tm_now;
  now = time(NULL); //assigning Time to 'now'.
  tm_now = localtime(&now); //assigning Local time to 'tm_now'.
  cout<<ctime(&now); //and printing.
  cout<<asctime(tm_now); //printing 'tm_now' value.
 getch();
}
Output
Wed May 10 03:42:13 2023
Wed May 10 03:42:13 2023

Program Printing Complete Current Data and Time Another Method

Program

#include<iostream.h>
#include<conio.h>
#include<Windows.h> //including Library for working with Windows.
void main()
{
	SYSTEMTIME str_t; //'str_t' is object of 'SYSTEMTIME'.
	GetSystemTime(&str_t); //getting System Time. and printing.
	cout<<"Year: "<<str_t.wYear<<endl<<"Month: "<<str_t.wMonth<<endl<<
   "Date: "<<str_t.wDay<<endl<<"Hour: "<<str_t.wHour<<endl<<"Min: "<<
   str_t.wMinute<<endl<<"Second: "<<str_t.wSecond;
  getch();
}
Output
Year: 2023
Month: 5
Date: 9
Hour: 22
Min: 42
Second: 46

Program User Enter Date Using as a Computer Date

Program

#include<iostream.h>
#include<conio.h>
#include<time.h> //including Library for working with Time.
void main()
{
    tm str_time; //'str_time' is object.
		time_t time_of_day; //'time_of_day' is object of 'time_t'.
		str_time.tm_year = 2012-1900; //assigning values.
		str_time.tm_mon = 6;
		str_time.tm_mday = 5;
		str_time.tm_hour = 10;
		str_time.tm_min = 3;
		str_time.tm_sec = 5;
		str_time.tm_isdst = 0;
		time_of_day = mktime(&str_time); //assigning new date.
      cout<<ctime(&time_of_day); //and printing.
  getch();
}
Output
Thu Jul 05 10:03:05 2012