C++ 获取时间戳:下周一、月初、月中、月末
在一次开发过程中需要利用当前时间获取下周一、这个个月月中、这个月月末和下个月月初的时间戳,在此做一个总结。
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <time.h>
#define ONE_DAY (86400)
using namespace std;
int GetWeek(long now_timestamp) {
struct tm gmtm;
gmtime_r(&now_timestamp, &gmtm);
int day_of_week = gmtm.tm_wday;
return day_of_week == 0?7:day_of_week;
}
int GetDay(long now_timestamp) {
struct tm gmtm;
gmtime_r(&now_timestamp, &gmtm);
int day_of_month = gmtm.tm_mday;
return day_of_month;
}
int GetYears(long now_timestamp) {
struct tm gmtm;
gmtime_r(&now_timestamp, &gmtm);
int years = gmtm.tm_year;
return years;
}
int GetMonth(long now_timestamp) {
struct tm gmtm;
gmtime_r(&now_timestamp, &gmtm);
int month = gmtm.tm_mon;
return month;
}
int GetDaysInMonth(long now_timestamp)
{
int now_years = GetYears(now_timestamp);
int now_month = GetMonth(now_timestamp);
int now_day;
int day[]= {31,28,31,30,31,30,31,31,30,31,30,31};
if (1 == now_month){
now_day=(((0==now_years%4)&&(0!=now_years%100)||(0==now_years%400))?29:28);
}
else{
now_day=day[now_month];
}
return now_day;
}
int main(int argc, char *argv[]){
long now_time = time(NULL);
long now_floor_time = now_time/ONE_DAY*ONE_DAY;
cout << "now time: " << now_floor_time << endl;
//获取下一个周一零点时间
cout << "next Monday time: " << now_floor_time + (8 - GetWeek(now_time))*ONE_DAY << endl;
//获取这个月中旬或者这个月末时间
long now_day_of_month = GetDay(now_time);
if (now_day_of_month < 15) {
cout << "next Mid-month time: " << now_floor_time + (15 - now_day_of_month)*ONE_DAY << endl;
}
else {
cout << "next End of month time: " << now_floor_time + (GetDaysInMonth(now_time) - now_day_of_month)*ONE_DAY << endl;
}
//获取下个月月初时间
cout << "next month time: " << now_floor_time + (GetDaysInMonth(now_time) - now_day_of_month+1)*ONE_DAY << endl;
}
在上述代码中gmtime_r()方法可以线程安全获取到关于当前时间的一个结构体tm,返回的月份从0-11,返回每个月所在的日期为1-31,返回的所在礼拜为0-6,其中0代表的是礼拜天,1代表礼拜一以此类推;
struct tm
{
int tm_sec; // seconds after the minute - [0, 60] including leap second
int tm_min; // minutes after the hour - [0, 59]
int tm_hour; // hours since midnight - [0, 23]
int tm_mday; // day of the month - [1, 31]
int tm_mon; // months since January - [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday - [0, 6]
int tm_yday; // days since January 1 - [0, 365]
int tm_isdst; // daylight savings time flag
};
通过获取到的年份,判断当前年份是否是闰年来获取每个月对应的天数,方法如 GetDaysInMonth();
拿到这些信息我们可以通过计算天数来获取自己所需要的时间戳。
运行结果如下:
now time: 1560211200
next Monday time: 1560729600
next Mid-month time: 1560556800
next month time: 1561939200