【分解的时间 struct tm】
struct tm 是linux中用来保存分解时间的数据结构。其定义在time.h中,可通过下面命令找到
$whereis time.h
其结构定义如下,基本都是整型的。有几点需要注意的
1、tm_sec 表示秒,除了0~59秒,可以取值60,主要是考虑leap second,即闰秒
2、tm_mday 是从1开始的,表示一个月的天数,最大31
3、tm_mon 是从0开始的,即0 表示1月。
4、tm_year 是现在的年份-1900得到的数字
5、tm_yday 是从0开始的,最大365,即可表示闰年
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]*/
long int tm_gmtoff; /* Seconds east of UTC. */
__const char *tm_zone; /* Timezone abbreviation. */
long int __tm_gmtoff; /* Seconds east of UTC. */
__const char *__tm_zone; /* Timezone abbreviation. */
};
【strftime 实现定制字符串】
strftime的函数原型同样定义在time.h中
extern size_t strftime (char *__restrict __s,
size_t __maxsize,
__const char *__restrict __format,
__const struct tm *__restrict __tp);
该函数有4个参数,
char型的指针:通常可以定义一个 char类型的数组来传递该参数
char myStr[255]="\0";
size_t 的大小:可以使用 sizeof 来实现,即
sizeof(myStr)
const char* 类型的format:常常用于控制格式,例如
string myFormat = "%Y-%m-%d:%H:%M:%S"
最后一个参数为传入的 struct tm 数据类型。需要传递一个指针。
【代码示例】
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int main()
{
struct tm mytmstruct;
mytmstruct.tm_sec=33;
mytmstruct.tm_min=28;
mytmstruct.tm_hour=14;
mytmstruct.tm_mday=24; //24号
mytmstruct.tm_mon=6; //这里表示7月
mytmstruct.tm_year=118; //注意这里是118,118+1900=2018
string myFormat = "%Y-%m-%d:%H:%M:%S"; //自定义格式
char myStr[255]="\0"; //strftime 第一个参数是 char *
strftime(myStr,sizeof(myStr),myFormat.c_str(),&mytmstruct); //myFormat.c_str() 兼容c字符串,c中没有string类型
cout<<"myStr is:" <<myStr <<endl;
编译执行结果如下
$gcc -lstdc++ l_csdn_tm2str.cpp -o tm2str
$./tm2str
myStr is:2018-07-24:14:28:33