c++时间和日期
时间是一个结构体,如下:
struct tm {
int tm_sec; // seconds after the minute [0-60]
int tm_min; // minutes after the hour [0-59]
int tm_hour; // hours since midnight [0-23]
int tm_mday; // day of the month [1-31]
int tm_mon; // months since January [0-11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday [0-6]
int tm_yday; // days since January 1 [0-365]
int tm_isdst; // Daylight Savings Time flag
long tm_gmtoff; // offset from CUT in seconds
char *tm_zone; // timezone abbreviation
};
c++标准库有如下常用函数:
time_t time(time_t * time);//该函数返回当前日历时间,自1970年1月1日以来经过的秒数。
char* ctime(const time_t * time);//返回一个字符串指针,字符串形式:day month year hours:minutes:seconds year\n\0。
struct tm * localtime(const time_t * time);//返回一个指向本地时间的tm结构体指针。
char* asctime(const struct tm* time);//类似ctime的效果。
struct tm * gmtime(const time_t * time);//返回格林尼治时间,时间格式和ctime是是一样的。
time_t mktime(struct tm* time);//返回当前时间。
double difftime(time_t time2,time_t time1);//返回time1和time2之间相差的秒数。
size_t strftime();//用于格式化日期和时间。
#include <time.h>
#include <ctime>
int main(int argc, const char * argv[]) {
time_t now = time(0);//time_t time(time_t * time);返回系统当前日历时间,自1970,1,1以来经过的秒数,如果系统没有时间,则返回1.
char* dt = ctime(&now);//char *ctime(const time_t *);返回表示当地时间的字符串指针,格式: day month year hours:minutes:seconds year\n\0。
cout<<"本地日期"<<dt<<endl;
//把now转换为tm结构
tm* tm = gmtime(&now);//转换成世界时间,格林尼治时间
dt = asctime(tm);//该函数的作用和ctime是一样的,这两个函数的区别就是参数的不同。这个函数参数是一个结构体指针
cout<<"utc 日期和时间"<<dt<<endl;
cout<<"year: "<<1900 + tm->tm_year<<endl;
cout<<"month: "<<1+ tm->tm_mon<<endl;
cout<<"day: "<<tm + tm->tm_mday<<endl;
cout<<"Time: "<<1 + tm->tm_hour<<":";
cout<<1+ tm->tm_min<<":";
cout<<1+ tm->tm_sec<<endl;
return 0;
};
随机数
//创建随机数种子
void XXX::createReed()
{
time_t tt;
time(&tt);
struct tm* now;
now = localtime(&tt);
timeval tv;
gettimeofday(&tv,NULL);
unsigned int reed = (unsigned int)(tv.tv_sec*1000+tv.tv_usec/1000);
log("reed:%d",reed);
srand(reed);
}
//创建区间随机数
int XXX::getRandomNumber(int start, int end)
{
createReed();
return CCRANDOM_0_1()*(end-start)+start;
}
//获取最后随机数
int XXX::getFinalRandom()
{
int random = getRandomNumber(0, 10);
return random;
}