c++ 时间和日期、随机数—— c++复习(四)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值