时间模块需要引入time.h头文件

#include <time.h>

 

1. c获取时间戳

#include <stdio.h>
#include <time.h>

// 格林威治时间戳

void my_time(){
    // 这里最好是long int
    int time1 = 0;
    // 方法1
    time(&time1);
    printf("time1 is :%d \n", time1); // time1 is :1548137793

    // 方法2
    time_t time2 = 0;
    time2 = time(NULL);
    printf("time2 is :%d \n", time2); // time1 is :1548137793

}

int main(){
    my_time();
    return 0;
}

 

2. c 获得时间字符串,或者将时间戳转换成字符串

#include<stdio.h>
#include<time.h>

#define N 20
int main( void ) { struct tm *newtime; char tmpbuf[N]; time_t test; time(&test); printf("%d\n", test); // 1548138728 // 将时间戳转换成字符串 newtime=localtime(&test); strftime(tmpbuf, N, "%Y-%m-%d %H:%M:%S\n", newtime); printf(tmpbuf); // 2019-01-22 14:32:08 return 0; }

 

那为什么呢?C语言定义了结构体struct tm

/* ISO C `broken-down time' structure.  */
struct tm
{
  int tm_sec;            /* Seconds.    [0-60] (1 leap second) */
  int tm_min;            /* Minutes.    [0-59] */
  int tm_hour;            /* Hours.    [0-23] */
  int tm_mday;            /* Day.        [1-31] */
  int tm_mon;            /* Month.    [0-11] */
  int tm_year;            /* Year    - 1900.  */
  int tm_wday;            /* Day of week.    [0-6] */
  int tm_yday;            /* Days in year.[0-365]    */
  int tm_isdst;            /* DST.        [-1/0/1]*/

# ifdef    __USE_MISC
  long int tm_gmtoff;        /* Seconds east of UTC.  */
  const char *tm_zone;        /* Timezone abbreviation.  */
# else
  long int __tm_gmtoff;        /* Seconds east of UTC.  */
  const char *__tm_zone;    /* Timezone abbreviation.  */
# endif
};
源码

相关文章:

  • 2021-05-25
  • 2021-05-18
猜你喜欢
  • 2022-12-23
  • 2021-10-06
  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
相关资源
相似解决方案