C++/Development/Time

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Output a time value with ctime

<source lang="cpp">

  1. include <iostream>
  2. include <ctime>

using namespace std; int main () {

   time_t rawtime;
   time ( &rawtime );
   cout << "Current date and time is: "<< ctime  (&rawtime);
   return 0;

}


 </source>


Overload date() for time_t.

<source lang="cpp">

  1. include <iostream>
  2. include <cstdio>
  3. include <ctime>

using namespace std; class date {

 int day, month, year;

public:

 date(char *str);
 date(int m, int d, int y) {
   day = d;
   month = m;
   year = y;
 }
 date(time_t t);
 void show() {
   cout << month << "/" << day << "/";
   cout << year << "\n";
 }

};

date::date(char *str) {

 sscanf(str, "%d%*c%d%*c%d", &month, &day, &year);

} date::date(time_t t) {

 struct tm *p;
 p = localtime(&t); // convert to broken down time
 day = p->tm_mday;
 month = p->tm_mon;
 year = p->tm_year;

} int main() {

 date sdate("12/31/06");    // construct date object using string
 date idate(12, 31, 04);    // construct date object using integers
 date tdate(time(NULL));
 sdate.show();
 idate.show();
 tdate.show();
 
 return 0;

}


 </source>


Use system time

<source lang="cpp">

  1. include <iostream>
  2. include <ctime>

using namespace std; class TimeDate {

 time_t systime;

public:

 TimeDate(time_t t); // constructor
 void show();

}; TimeDate::TimeDate(time_t t) {

 systime = t;

} void TimeDate::show() {

 cout << ctime(&systime);

} int main() {

 time_t x;
 x = time(NULL);
 TimeDate ob(x);
 ob.show();
 return 0;

}


 </source>


Using ctime() to get the current time

<source lang="cpp">

  1. include <time.h>
  2. include <iostream>

using namespace std; int main() {

  time_t currentTime;
  // get and print the current time
  time (&currentTime); // fill now with the current time
  cout << "It is now " << ctime(&currentTime) << endl;
  struct tm * ptm= localtime(&currentTime);
  cout << "Today is " << ((ptm->tm_mon)+1) << "/";
  cout << ptm->tm_mday << "/";
  cout << ptm->tm_year << endl;
  cout << "\nDone.";
  return 0;

}


 </source>