前言
获取本机时间,和获得其他时间节点 C语言风格
内容
获取本地时间
std::time_t now = std::time(nullptr);
std::tm *ptm = std::localtime(&now);
// 时间转字符串
std::stringstream ss;
ss << std::put_time(ptm, "%Y%m%d"); // 格式 年月日
cout << ss.str() << endl;
获取前一天的日期和时间
void getLastDay(void)
{
std::time_t now = std::time(nullptr);
std::tm *ptm = std::localtime(&now);
ptm->tm_mday -= 1;
std::mktime(ptm);
std::stringstream ss;
ss << std::put_time(ptm, "%Y-%m-%d-%H-%M-%S");
cout << ss.str() << endl;
}
获取当前日期所在周的周一的日期
void GetWeekFirstDayString(void)
{
time_t now = time(nullptr);
std::tm *ptm = localtime(&now);
int days = ptm->tm_wday;
if (0 == days) // 周日是0
days = 7;
ptm->tm_mday -= days - 1;
std::mktime(ptm);
std::stringstream ss;
ss << std::put_time(ptm, "%Y%m%d");
}
获取当前日期所在月的第一天的日期
void getLastDay(void)
{
std::time_t now = std::time(nullptr);
std::tm *ptm = std::localtime(&now);
ptm->tm_mday = 1;
std::stringstream ss;
ss << std::put_time(ptm, "%Y-%m-%d-%H-%M-%S");
cout << ss.str() << endl;
}
std::tm是一个结构体,当你对其中成员进行修改后,使用std::mktime函数将日期与时间结构体转换成时间戳;在上述代码中,获取日期所在周的周一的日期中,我们对tm_day进行了运算。如果当tm_day为负数,在使用mktime函数后,能够自动帮我们修正,例如 2024-08-01是周斯,该周的周一是2024-07-29;
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};