从 boost ptime 获取年份

发布于 2024-08-04 18:39:35 字数 931 浏览 1 评论 0原文

我正在将现有程序转换为 C++,这里需要操作 Sybase 时间戳。这些时间戳包含日期和时间信息,据我所知,最好通过 boost::posix_time::ptime 变量来处理这些信息。在代码中的一些地方,我需要从变量中获取年份。

我的问题是:如何最有效地从 boost ptime 变量中提取年份?下面是一个示例程序,其中需要行代码,并具有额外的ostringstream变量和boost::gregorian::date的开销代码>变量。

根据升压文档:

类 ptime 依赖于 gregorian::date 的接口 时间点的日期部分

,但是 gregorian::date 似乎不是 ptime 的基类。不知怎的,我在这里遗漏了一些东西。

难道没有更简单的方法从 ptime 中提取年份吗?

样本:

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   boost::posix_time::ptime t(boost::posix_time::second_clock::local_time());
   boost::gregorian::date d = t.date();
   std::ostringstream os; os << d.year();
   std::cout << os.str() << std::endl;
   return 0;
}

I'm converting an existing program to C++ and here need to manipulate Sybase timestamps. These timestamps contain date and time info, which to my knowledge can be best handled by a boost::posix_time::ptime variable. In a few places in the code I need to get the year from the variable.

My question is: how can I most efficiently extract the year from a boost ptime variable? Below is a sample program in which it takes three lines of code, with the overhead of an extra ostringstream variable and a boost::gregorian::date variable.

According to boost documentation:

Class ptime is dependent on gregorian::date for the interface to the
date portion of a time point

however gregorian::date doesn't seem to be a base class of ptime. Somehow I'm missing something here.

Isn't there an easier way to extract the year from the ptime?

Sample:

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   boost::posix_time::ptime t(boost::posix_time::second_clock::local_time());
   boost::gregorian::date d = t.date();
   std::ostringstream os; os << d.year();
   std::cout << os.str() << std::endl;
   return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贱人配狗天长地久 2024-08-11 18:39:35

跳过 ostringstream。否则,您可能会受益于“使用命名空间...”

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   using namespace boost::posix_time;
   std::cout << second_clock::local_time().date().year() << std::endl;
   return 0;
}

Skip the ostringstream. Otherwise, you may benefit from "using namespace..."

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   using namespace boost::posix_time;
   std::cout << second_clock::local_time().date().year() << std::endl;
   return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文