Obtaining the Current Date and Time, Getting the local and UTC times - C++ Data Type

C++ examples for Data Type:time

Description

Obtaining the Current Date and Time, Getting the local and UTC times

Demo Code

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {//from w  w w.j a v  a2s  .c o  m
  // Current date/time based on current system
  time_t now = time(0);

  // Convert now to tm struct for local timezone
  tm* localtm = localtime(&now);

  cout << "The local date and time is: " << asctime(localtm) << endl;

  // Convert now to tm struct for UTC
  tm* gmtm = gmtime(&now);
  if (gmtm != NULL) {
     cout << "The UTC date and time is: " << asctime(gmtm) << endl;
  }
  else {
    cerr << "Failed to get the UTC date and time" << endl;
    return EXIT_FAILURE;
  }
}

Result

Layout of a tm struct

struct tm {
  int tm_sec;   // seconds of minutes from 0 to 61 (60 and 61 are leap seconds)
  int tm_min;   // minutes of hour from 0 to 59
  int tm_hour;  // hours of day from 0 to 24
  int tm_mday;  // day of month from 0 to 23
  int tm_mon;   // month of year from 0 to 11
  int tm_year;  // year since 1900
  int tm_wday;  // days since sunday
  int tm_yday;  // days since January 1st
  int tm_isdst; // hours of daylight savings time
}

Related Tutorials