21xrx.com
2025-07-10 00:55:12 Thursday
登录
文章检索 我的文章 写文章
使用C++获取当前年月的上个月
2023-07-05 07:32:34 深夜i     32     0
C++ 获取当前年月 上个月

在C++中,获取当前年月的上个月可以通过日期和时间库中的函数来实现。下面将介绍如何使用库函数来获取上个月的年份和月份。

首先,我们需要包含日期和时间库的头文件。例如,使用C++11标准的代码如下:

#include <iostream>
#include <chrono>
#include <ctime>

接着,我们可以使用std::chrono::system_clock::now()函数来获取当前时间。该函数返回的是一个时间点对象,表示自1970年1月1日以来的秒数个数。

auto now = std::chrono::system_clock::now();

我们可以将这个时间点转化为UTC时间,并使用std::tm结构体来获取年份和月份。

auto utc_time = std::chrono::system_clock::to_time_t(now);
auto local_time = std::localtime(&utc_time);
int current_year = local_time->tm_year + 1900;
int current_month = local_time->tm_mon + 1;

这里需要注意的是,std::tm结构体中保存的月份是0到11,表示1到12月,因此我们需要将月份加1才能得到正确的月份。同时,std::tm结构体中的年份表示自1900年以来的年数,因此我们需要将年份加上1900才能得到当前年份。

接下来,我们可以将当前月份减1,来得到上个月的月份。同时,如果当前月份为1月,我们需要将年份减1,并将月份设置为12月。

int last_month = current_month - 1;
int last_year = current_year;
if(last_month < 1)
  last_month = 12;
  last_year--;

最后,我们可以输出上个月的年份和月份。

std::cout<<"Last month's year is "<<last_year<<", month is "<<last_month<<std::endl;

完整的代码如下:

#include <iostream>
#include <chrono>
#include <ctime>
int main(){
  auto now = std::chrono::system_clock::now();
  auto utc_time = std::chrono::system_clock::to_time_t(now);
  auto local_time = std::localtime(&utc_time);
  int current_year = local_time->tm_year + 1900;
  int current_month = local_time->tm_mon + 1;
  int last_month = current_month - 1;
  int last_year = current_year;
  if(last_month < 1)
    last_month = 12;
    last_year--;
  
  std::cout<<"Last month's year is "<<last_year<<", month is "<<last_month<<std::endl;
  return 0;
}

在实际应用中,我们可以将上面的代码封装成函数,以便在多处调用。例如,可以写一个名为get_last_month的函数,该函数返回上个月的年份和月份。函数定义如下:

std::pair<int, int> get_last_month(){
  auto now = std::chrono::system_clock::now();
  auto utc_time = std::chrono::system_clock::to_time_t(now);
  auto local_time = std::localtime(&utc_time);
  int current_year = local_time->tm_year + 1900;
  int current_month = local_time->tm_mon + 1;
  int last_month = current_month - 1;
  int last_year = current_year;
  if(last_month < 1)
    last_month = 12;
    last_year--;
  
  return std::make_pair(last_year, last_month);
}

在调用get_last_month函数的时候,我们可以得到上个月的年份和月份。

auto last_month = get_last_month();
std::cout<<"Last month's year is "<<last_month.first<<", month is "<<last_month.second<<std::endl;

通过使用C++日期和时间库,我们可以非常方便地获取当前年月的上个月,实现起来非常简便。在实际应用中,我们可以将上述代码封装成函数,方便进行调用。

  
  

评论区