Home » C++ programs » C++ Most popular & searched programs

Reading date and time from Linux operating system using C++ program

Learn: How to get current date and time from Linux Operating System using C++ program? This program will read date, time from Operating system and print on the standard output device.

This C++ program is reading date and time from Linux Operating System, this program is compiled and executed on G++ compiler and compatible for only Linux Operating System based devices.

To extract current date and time, we are using localtime() function.

In this program, we are also going to use time.h and sys/time.h header files, which has definition os related structure.

Consider the program:

#include <iostream>
using namespace std;

#include <getopt.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

//function to read date and time from Linux OS
void readOsDateTime(int *date, int *month,int *year, int *hour, int *min, int *sec, int *wday)
	time_t current = time(NULL);
	struct tm *current_s = localtime(&current);

	if(current_s != NULL)
		*date  =  current_s	->tm_mday;
		*month =  ++current_s	->tm_mon;
		*year  =  current_s	->tm_year;

			*year = *year - 100;

		*hour  = current_s	->tm_hour;
		*min   = current_s	->tm_min;
		*sec   = current_s	->tm_sec;
		*wday  = current_s	->tm_wday;

//main function
int main()
	//init all variable to 0
	int date   =0;
	int month  =0;
	int year   =0;
	int hour   =0;
	int min    =0;
	int sec    =0;
	int wday   =0;

	//define weekdays names
	char *Names[] = {"Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};

	//function call that will assign date and time in variables
	readOsDateTime(&date, &month, &year, &hour, &min, &sec, &wday);
	//printing the date
	cout<<date<<"/"<<month<<"/"<<year+2000<<"  "<<hour<<":"<<min<<":"<<sec<<"  "<<Names[wday];
	return 0;


11/7/2017  18:47:54  Tuesday


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.