//头文件
#include<time.h>
//时间结构
struct tm
{
int tm_sec; /*秒-取值区间为[0,59]*/
int tm_min; /*分-取值区间为[0,59]*/
int tm_hour; /*时-取值区间为[0,23]*/
int tm_mday; /*一个月中的日期-取值区间为[1,31]*/
int tm_mon; /*月份(从一月开始,0代表一月)-取值区间为[0,11],实际月份-1*/
int tm_year; /*年份,其实等于实际年份减去1900*/
int tm_wday; /*星期,取值区间为[0,6],其中0代表星期天,1代表星期一*/
int tm_yday; /*从每年的1月1日开始的天数-取值区间为[0,365],其中0代表1月1日*/
int tm_isdst; /*夏令时标识符,实行夏令时,tm_isdst为正,否则为负*/
}
1.时间戳转为时间结构
time_t nowtime=time(NULL); //获取系统当前时间的时间戳
tm *tm_c=localtime(&nowtime);
int tm_hour=tm_c->tm_hour;
int tm_min=tm_c->tm_min;
3.时间结构转为时间戳
- 作用:将时间转换为自1970年1月1日以来逝去时间的秒数,发生错误时返回-1。
time_t mktime(struct tm*)
eg.
time_t nowtime = time(NULL);
tm *tm_c;
tm_c = localtime(&nowtime);
tm_c->tm_hour=1;
tm_c->tm_min=2;
long casetime = mktime(tm_c);
4.根据288点计算当前时间戳
//输入时间点,返回该点时间戳
long time_trans(int n)
{
time_t t = time(NULL);
struct tm *tm = localtime(&t);
int min_val = n * 5;
int hour = min_val / 60;
int min = min_val % 60;
tm->tm_hour = hour;
tm->tm_min = min;
tm->tm_sec = 0;
return mktime(tm);
}
5.根据当前时刻,确定为288的哪个点
int GetNowPoint()
{
long now_time = time(NULL);
struct tm *tm_over;
tm_over = localtime(&now_time);
int hour = tm_over->tm_hour;
int min = tm_over->tm_min;
int now_point = ceil((hour * 60 + min) / 5);
return now_point;
}
6.按照时间格式输出
const string DateTimeString(const long t)
{
struct tm tm_p = { 0 };
localtime_r(&t, &tm_p);
char time_char[32] = {0};
sprintf(time_char,"%4d-%02d-%02d %02d:%02d:%02d",tm_p.tm_year+1900,tm_p.tm_mon+1,tm_p.tm_mday,tm_p.tm_hour,tm_p.tm_min,tm_p.tm_sec);
string time_str = string(time_char);
return time_str;
}
const string DateTimeString3(const long t)
{
struct tm tm_p = { 0 };
localtime_r(&t, &tm_p);
char time_char[32] = {0};
sprintf(time_char,"%4d-%02d-%02d",tm_p.tm_year+1900,tm_p.tm_mon+1,tm_p.tm_mday);
string time_str = string(time_char);
return time_str;
}