用boost检索当前世纪

Retrieve current century with boost

本文关键字:boost 检索      更新时间:2023-10-16

我可以通过调用

来检索当前年份:
boost::posix_time::second_clock::local_time().date().year(); 

但是我如何用boost函数从那一年提取世纪数呢?

一个世纪在所有地区的定义都是100年。然而,问题是本世纪何时开始。(你是从0开始数还是从1开始数?)假设是格里高利历,或者是一个与教皇格雷格一致的关于何时开始计数的日历:

#include <iostream>
int yearToCentury(int year)
{
    return (year + 99) / 100;
}
int main()
{
    std::cout << 1999 << ": " << yearToCentury(1999) << std::endl;
    std::cout << 2000 << ": " << yearToCentury(2000) << std::endl;
    std::cout << 2001 << ": " << yearToCentury(2001) << std::endl;
    return 0;
}

产生如下结果:

1999: 20
2000: 20
2001: 21

但是,我在标准库或boost中找不到任何函数为您完成此计算的证据。

除以100有什么不对?

首先使用boost获取当前日期时间:

boost::posix_time::ptime timeLocal = boost::posix_time::second_clock::local_time();
auto century = GetCentury(timeLocal.date().year());
获取当前世纪的方法:
/// <summary>Gets century from year.</summary>
/// <param name="year">The year.</param>
/// <returns>The century as int value.</returns>
int GetCentury(int year)
{
    if (year % 100 == 0)
        return year / 100;
    else
        return year / 100 + 1;
}