C++日期时间函数

获取毫秒时间戳

int64_t GetMilliSecond()
{
    return ::chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
}

获取秒级时间戳

int32_t GetSecond()
{
	return ::chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
}

获取秒级时间戳(根据给定的年、月、日、时、分、秒)

int32_t GetSecond(int year, int month, int day, int hour, int minute, int second)
{
	tm tm_;                                    // 定义tm结构体。
	tm_.tm_year = year - 1900;                 // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
	tm_.tm_mon = month - 1;                   // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
	tm_.tm_mday = day;                      // 日。
	tm_.tm_hour = hour;                      // 时。
	tm_.tm_min = minute;                     // 分。
	tm_.tm_sec = second;                     // 秒。
	tm_.tm_isdst = 0;                       // 非夏令时。
	time_t t_ = mktime(&tm_);                  // 将tm结构体转换成time_t格式。
	return t_;                            
}

发表评论

邮箱地址不会被公开。 必填项已用*标注