C++

C++ Date & Time

C++ Date & Time

There is no separate date type in C++ standard library. It inherits the structs and functions for date and time manipulation from C. We need to include ctime header file to access date and time related functions and structures. There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.

In C++ 11 you can use std::chrono::system_clock::now()  to get current system date and time. Let us see this in an example. Copy this code in a file called computeTime.cpp. This code finds how much time system actually takes to calculate square of first 100 natural numbers.   

#include <iostream>
#include <chrono>
#include <ctime>    
#include <time.h>
#include <string.h>
int main()
{
    int i;
    int sq;
    struct tm tm;
    auto start = std::chrono::system_clock::now();
    for (i=1; i<=100; i++)
      sq = i * i; 
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    localtime_r(&end_time, &tm);
    char CharLocalTimeofUTCTime[30];
    strftime(CharLocalTimeofUTCTime, 30, "%Y-%m-%dT%H:%M:%SZ", &tm);
    //std::string strLocalTimeofUTCTime(CharLocalTimeofUTCTime);
    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

Now compile and execute this code.

(base) 0:28:05:~ % ./a.out            
finished computation at Sat Sep 25 00:28:06 2021
elapsed time: 1e-06s

The tm structure is very important while working with date and time both C and C++. Most of the time related functions makes use of tm structure. In the previus code snippet, we have used tm strucuture to convert time from UTC timezone to IST time zone.