×

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The < ctime > header file is

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The < ctime > header file is included in the application to utilize date and time in C++.

The following are the four time-related types in this header file:

  • The t-clock is an arithmetic type name and represents a type of clock. Represents a cold number in the clock (fixed time units with a certain system length). Retrieved type (clock /) t.
  • Time t is an abbreviated form of time. Represents the time returned by the time function (). If the time exceeds 00:00 hours, we subtract the total value as the number of seconds exceeds.
  • Size t indicates the size of any object by bytes and is a nickname for the type of the unsigned number. Task size () prints size and calculation, and output is size t.
  • tm - In the C structure, the tm structure saves the day and time. Described as follows-
struct time {  
    int time_sec; // seconds of minutes from 0 to 61  
    int time_min; // minutes of hour from 0 to 59  
    int time_hour; // hours of day from 0 to 24  
    int time_monday; // day of month from 1 to 31  
    int time_month; // month of year from 0 to 11  
    int time_year; // year since 1900  
    int time_wday; // days since sunday  
    int time_yday; // days since January 1st  
    int time_isdst; // hours of daylight savings time  
}  

C++ date and time functions

The function nameThe function prototypeThe function description
mktimetime_t mktime ( struct time *tm ) ;This function converts mktime to time t, which is the calendar date and time format.
ctimechar *ctime ( const time_t *tm ) ;It gives you a reference to a string with the following format: day month year hours: minutes: seconds year.
difftimedouble difftime ( time_t time2, time_t time1 ) ;The difference between two time objects t1 and t2 is returned.
gmtimestruct time *gmtime ( const time_t *time ) ;This method returns a reference to the time in structure format. The time is in UTC (Universal Coordinated Time).
clockclock_t clock ( void ) ;It offers a rough estimate of how long the caller application has been running. If the value is not accessible, the value.1 is returned.
localtimestruct time *localtime ( const time_t *time ) ;The pointer to the tm structure, which represents local time, is returned by this method.
timetime_t time ( time_t *time ) ;It is the current time.
strftimesize_t strftime ( ) ;We may format date and time in a certain way with the aid of this function.
asctimechar * asctime ( const struct tm * time ) ;The function transforms the tm type object to a string and returns the string's pointer.

The example below shows how to print the current date and time in UTC format:

#include < ctime >   
#include < iostream >  
#include < bits/stdc++.h >
#include < stdlib >
#include < stdio >
using namespace std ;  
int main ( )  
{  
    time_t now = time ( 0 ) ; // get current dat/time with respect to system  
    char* dt = ctime ( &now ) ; // convert it into string  
    cout << "The local date and time is: " << dt << endl ; // print local date and time  
    tm* gmtm = gmtime(&now); // for getting time to UTC convert to struct  
    dt = asctime ( gmtm ) ;  
    cout << "The UTC date and time is:" << dt << endl ; // print UTC date and time  
    return 0;
}

OUTPUT:

The local date and time is: Wed Jun 15 20:19:40 2022
The UTC date and time is: Wed Jun 15 20:19:40 2022
………………………………………………………………………………..
Process executed in 2.33 seconds
Press any key to continue.

Explanation:

In the above example of a program in C++, we have used a header file named ctime to find the current date and time, time_t get our current date and time with re4spect to the system.

The code below shows how to split the tm structure and output each attribute separately using the -> operator:

#include <iostream>  
#include <ctime>  
using namespace std;  
int main()  
{  
    time_t now = time(0); // get current date and time  
    cout << "Number of seconds sinceJune 1, 2022 is:: " << now << endl;  
    tm* ltm = localtime(&now);  
    // print various components of tm structure.  
    cout << "Year:" << 1900 + ltm->tm_year << endl; // print the year  
    cout << "Month: " << 1 + ltm->tm_mon << endl; // print month number  
    cout << "Day: " << ltm->tm_mday << endl; // print the day  
    // Print time in hour:minute:second  
    cout << "Time: " << 5 + ltm->tm_hour << ":";  
    cout << 30 + ltm->tm_min << ":";  
    cout << ltm->tm_sec << endl;  
    return 0;
}  

OUTPUT:

Number of seconds since June 1, 2022 is:: 1632328
Year:2022
Month: 6
Day: 15
Time: 22:40:53
................................................
Process executed in 2.22 seconds
Press any key to continue.

Explanation:

In the above example of a code in C++, we have shown how to split the tm structure and output each attribute separately using the -> operator.

included in the application to utilize date and time in C++.

The following are the four time-related types in this header file:

  • The t-clock is an arithmetic type name and represents a type of clock. Represents a cold number in the clock (fixed time units with a certain system length). Retrieved type (clock /) t.
  • Time t is an abbreviated form of time. Represents the time returned by the time function (). If the time exceeds 00:00 hours, we subtract the total value as the number of seconds exceeds.
  • Size t indicates the size of any object by bytes and is a nickname for the type of the unsigned number. Task size () prints size and calculation, and output is size t.
  • tm - In the C structure, the tm structure saves the day and time. Described as follows-
struct time {  
    int time_sec; // seconds of minutes from 0 to 61  
    int time_min; // minutes of hour from 0 to 59  
    int time_hour; // hours of day from 0 to 24  
    int time_monday; // day of month from 1 to 31  
    int time_month; // month of year from 0 to 11  
    int time_year; // year since 1900  
    int time_wday; // days since sunday  
    int time_yday; // days since January 1st  
    int time_isdst; // hours of daylight savings time  
}  

C++ date and time functions

The function nameThe function prototypeThe function description
mktimetime_t mktime ( struct time *tm ) ;This function converts mktime to time t, which is the calendar date and time format.
ctimechar *ctime ( const time_t *tm ) ;It gives you a reference to a string with the following format: day month year hours: minutes: seconds year.
difftimedouble difftime ( time_t time2, time_t time1 ) ;The difference between two time objects t1 and t2 is returned.
gmtimestruct time *gmtime ( const time_t *time ) ;This method returns a reference to the time in structure format. The time is in UTC (Universal Coordinated Time).
clockclock_t clock ( void ) ;It offers a rough estimate of how long the caller application has been running. If the value is not accessible, the value.1 is returned.
localtimestruct time *localtime ( const time_t *time ) ;The pointer to the tm structure, which represents local time, is returned by this method.
timetime_t time ( time_t *time ) ;It is the current time.
strftimesize_t strftime ( ) ;We may format date and time in a certain way with the aid of this function.
asctimechar * asctime ( const struct tm * time ) ;The function transforms the tm type object to a string and returns the string's pointer.

The example below shows how to print the current date and time in UTC format:

#include < ctime >   
#include < iostream >  
#include < bits/stdc++.h >
#include < stdlib >
#include < stdio >
using namespace std ;  
int main ( )  
{  
    time_t now = time ( 0 ) ; // get current dat/time with respect to system  
    char* dt = ctime ( &now ) ; // convert it into string  
    cout << "The local date and time is: " << dt << endl ; // print local date and time  
    tm* gmtm = gmtime(&now); // for getting time to UTC convert to struct  
    dt = asctime ( gmtm ) ;  
    cout << "The UTC date and time is:" << dt << endl ; // print UTC date and time  
    return 0;
}

OUTPUT:

The local date and time is: Wed Jun 15 20:19:40 2022
The UTC date and time is: Wed Jun 15 20:19:40 2022
………………………………………………………………………………..
Process executed in 2.33 seconds
Press any key to continue.

Explanation:

In the above example of a program in C++, we have used a header file named ctime to find the current date and time, time_t get our current date and time with re4spect to the system.

The code below shows how to split the tm structure and output each attribute separately using the -> operator:

#include <iostream>  
#include <ctime>  
using namespace std;  
int main()  
{  
    time_t now = time(0); // get current date and time  
    cout << "Number of seconds sinceJune 1, 2022 is:: " << now << endl;  
    tm* ltm = localtime(&now);  
    // print various components of tm structure.  
    cout << "Year:" << 1900 + ltm->tm_year << endl; // print the year  
    cout << "Month: " << 1 + ltm->tm_mon << endl; // print month number  
    cout << "Day: " << ltm->tm_mday << endl; // print the day  
    // Print time in hour:minute:second  
    cout << "Time: " << 5 + ltm->tm_hour << ":";  
    cout << 30 + ltm->tm_min << ":";  
    cout << ltm->tm_sec << endl;  
    return 0;
}  

OUTPUT:

Number of seconds since June 1, 2022 is:: 1632328
Year:2022
Month: 6
Day: 15
Time: 22:40:53
................................................
Process executed in 2.22 seconds
Press any key to continue.

Explanation:

In the above example of a code in C++, we have shown how to split the tm structure and output each attribute separately using the -> operator.


Related Topics

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.