C++/Development/Time
Содержание
Output a time value with ctime
#include <iostream>
#include <ctime>
using namespace std;
int main ()
{
time_t rawtime;
time ( &rawtime );
cout << "Current date and time is: "<< ctime (&rawtime);
return 0;
}
Overload date() for time_t.
#include <iostream>
#include <cstdio>
#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;
}
Use system time
#include <iostream>
#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;
}
Using ctime() to get the current time
#include <time.h>
#include <iostream>
using namespace std;
int main()
{
time_t currentTime;
// get and print the current time
time (¤tTime); // fill now with the current time
cout << "It is now " << ctime(¤tTime) << endl;
struct tm * ptm= localtime(¤tTime);
cout << "Today is " << ((ptm->tm_mon)+1) << "/";
cout << ptm->tm_mday << "/";
cout << ptm->tm_year << endl;
cout << "\nDone.";
return 0;
}