zoukankan      html  css  js  c++  java
  • c++日期和时间相关操作<time.h>(ctime)

    time.h(ctime)是c time library,定义了获取和操作日期和时间的函数。

    1. 结构

    typedef long time_t;

    time_t是长整型,表示的是距(1970年,1月1日08:00:00)的秒数,常常通过time函数获得。

    struct tm {
    int tm_sec; //秒 0-59(一般)
    int tm_min; //分 0-59
    int tm_hour; //小时0-23
    int tm_mday;//day 1-31
    int tm_mon; //月0-11
    int tm_year; // 距 1900 的年数 如2013-1900 = 113
    int tm_wday; //星期 0-6
    int tm_yday; //距1月1号天数,0-365
    int tm_isdst;

    tm包括日历日期和时间的各个组成

    2.函数

    time_t time ( time_t * timer );//获取当前时间
    time_t mktime ( struct tm * timeptr );//将struct tm转换为time_t
    struct tm * localtime ( const time_t * timer ); //将time_t转换为struct tm
    size_t strftime ( char * ptr, size_t maxsize, const char * format,
                      const struct tm * timeptr ); //将struct tm转换为特定格式的字符串输出
    char *strptime(const char *buf,const char *format,struct tm *timeptr); //将format形式的时间字符串转换为struct tm

      

    3.常用

    #include <time.h>
    time_t now;
    now = time(NULL);//获取当前时间
    
    struct tm *timeinfo;
    timeinfo = localtime(&now);//转换为tm
    
    time_t seconds;
    seconds = mktime(timeinfo);//转换为time_t
      time_t now = time(NULL);
      struct tm timeinfo = *localtime(&now);
      char buf[40];
      strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", &timeinfo);
      cout << buf << endl;//20130207142133
    
    
      strptime("20130207112305", "%Y%m%d%H%M%S", &timeinfo);
      cout << timeinfo.tm_sec << endl;//5
    

    4.获取当前时间的ms值

    #include <time.h>
    #include <sys/time.h>
    struct timeval tv;
    gettimeofday (&tv, NULL);
    uint64_t mseconds=tv.tv_sec * 1000 + tv.tv_usec / 1000;

    timeval用于指定时间值,结构如下

    timeval{
    time_t tv_sec; //秒 [long int]
    suseconds_t tv_usec; //微秒 [long int]
    };


    常用于计算一个方法的响应时间。

  • 相关阅读:
    Spring MVC Ajax 嵌套表单数据的提交
    Spring MVC 过滤静态资源访问
    Spring MVC 页面跳转时传递参数
    IDEA Maven 三层架构 2、运行 springMVC
    IDEA Maven 三层架构 1、基本的Archetype 搭建
    EasyUI DataGrid 基于 Ajax 自定义取值(loadData)
    Spring MVC Ajax 复杂参数的批量传递
    Mybatis Sql片段的应用
    在 Tomcat 8 部署多端口项目
    自动升级的设计思路与实现
  • 原文地址:https://www.cnblogs.com/whuqin/p/4982022.html
Copyright © 2011-2022 走看看