timezone converter in C++

Hey, guys today we are going to learn how to create a timezone converter in C++ using built-in functions only. Before starting with the code one should have basic knowledge of timezones. Universal Time Coordinated (UTC) or Greenwich Mean Time (GMT) is the time corresponding to 0 degrees (Prime Meridian).

Time changes one hour thus equivalent to a 1-hour difference in mean solar time for every 15 degrees East or West of Prime Meridian.  Thus the world is divided into different time zone accordingly. Local time refers to the time in your country.

Functions Used in the Program

Header file used: time.h

time.h header file describes 3 datatypes :
clock_t-It represents the date as an integer.
time_t -It represents clock time as an integer.
struct tm-It contains date and time with help of tm_sec,tm_hour,tm_min,tm_mday,tm_mon,tm_year,tm_wday,tm_yday

  • time(): It generates calendar time and stores it in time_t variable.
  • localtime(): It converts calendar time to broken-down time.
  •  gmtime(): It returns UTC time by taking calendar time as input.
  • asctime(): It returns a string by taking the struct tm variable as a parameter

Program: To Display local and UTC time and further creating a menu to change time between 5 time zones

#include<iostream.h>
#include<time.h>
void main()
{
int c;
//c is int variable used for receiving choice as input
time_t sys_time,sys_time2;
struct tm *local,*utc,*con_time;
//con_time is used for converted time.
sys_time=time(NULL);
local=localtime(&sys_time);
cout<<"Local time \t"<<asctime(local);
sys_time2=time(NULL);
utc=gmtime(&sys_time2);
cout<<"\n UTC time \t"<<asctime(utc);
cout<<"Please choose time zone from\n 1.Alaska \t 2.Central America \t 3.Greenland \t 4.Paris \t 5.Beijing\n";
cin>>c;
con_time=utc;
switch(c)
{
case 1:con_time->tm_hour=utc->tm_hour-9;
//time zone of alaska is -9.00
cout<<"\n Time in Alaska is "<<asctime(con_time);
break;
case 2:con_time->tm_hour=utc->tm_hour-6;
//time zone of Central America is -6.00
cout<<"\n Time in Central America is "<<asctime(con_time);
break;
case 3:con_time->tm_hour=utc->tm_hour-3;
//time zone of Greenland is -3.00
cout<<"\n Time in Greenland is "<<asctime(con_time);
break;
case 4:con_time->tm_hour=utc->tm_hour+1;
//time zone of Paris is +1.00
cout<<"\n Time in Paris is "<<asctime(con_time);
break;
case 5:con_time->tm_hour=utc->tm_hour+8;
//time zone of Beijing is +8.00
cout<<"\n Time in Beijing is "<<asctime(con_time);
break;
}
}

Output:

Local time   Wed Apr 22 18:59:04 2020

UTC time     Wed Apr 22 13:29:04 2020
Please choose time zone from
1.Alaska    2.Central America    3.Greenland    4.Paris    5.Beijing
4
Time in Paris is Wed Apr 22 14:29:04 2020

Also see:

Leave a Reply

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