我正在尝试编写一个函数,该函数可以为我提供两个时间戳之间存在的天数组。如何从时间戳间隔中获取天数列表
例如
getDays(int startTimestamp,int stopTimestamp);
输出将
2011-11-05
2011-11-06
2011-11-07
有反正在一个干净的方式这样做,而不必做一些繁重的算法中?
我对C++并不熟悉,所以我只想确保没有函数可以在我开始写大函数之前为我做这件事。
干杯
我正在尝试编写一个函数,该函数可以为我提供两个时间戳之间存在的天数组。如何从时间戳间隔中获取天数列表
例如
getDays(int startTimestamp,int stopTimestamp);
输出将
2011-11-05
2011-11-06
2011-11-07
有反正在一个干净的方式这样做,而不必做一些繁重的算法中?
我对C++并不熟悉,所以我只想确保没有函数可以在我开始写大函数之前为我做这件事。
干杯
有一个while循环
std::vector<std::string> dateList;
while (startTimestamp < stopTimestamp)
{
//Use strftime to convert startTimestamp to your format
// append to dateList
//increment startTimestamp by 1 day depending on what unit it is
}
strftime documenation。如果您的单位是time_t的,这是一个具体的例子
std::vector<std::string> getDays(time_t startTimestamp,time_t stopTimestamp)
{
std::vector<std::string> dateList;
char buffer[256];
while (startTimestamp < stopTimestamp)
{
struct tm * timeinfo;
timeinfo = localtime (&startTimestamp);
strftime (buffer,256,"%Y-%m-%d",timeinfo);
dateList.push_back(buffer);
startTimestamp += 24 * 60 * 60;
}
return dateList;
}
谢谢我会接受:) –
如果'startTimestamp'在某天的23:59:59,这将跳过最后一天, stopTimestamp'在其他日子的00:00:01。我不知道OP是否在意这一点。 –
localtime只是不是线程安全的...... :)我假设OP会在他剪切/粘贴我的代码前阅读一些文档 –
如果你要同时打印天的时候开始为“2011/11/18二十三时59分59秒”,而到底是“2011/11/19 00:00:01“,你可以开始对齐startTimestamp
到当天的午夜。
一天中有24*60*60
秒,所以你会做:
int const seconds_per_day = 24 * 60 * 60;
int alignedStart = startTimestamp - startTimestamp % seconds_per_day;
然后你循环从alignedStart
,直到你达到或走过去的stopTimestamp
,推进每次seconds_per_day
。
从阅读的文档,这应该在的C++ 0x的工作(但我没有得到一个兼容的编译器方便,以测试它自己):
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
using namespace std::chrono;
template <typename Clock>
void dayList(Clock from, Clock till)
{
for (Clock day=from; day<=till; day += hours(24))
{
std::time_t day_c = system_clock::to_time_t(day);
std::cout << std::put_time(std::localtime(&day_c), "%Y-%M-%D") << '\n';
}
}
int main()
{
time_point<system_clock>
from = system_clock::now(),
till = from + hours(190000);
dayList(from, till);
}
编辑This表明,你需要有VS2010
不同的实现,使用lambda函数转化计数迭代器(或者gcc4.7?):
#include <boost/iterator/counting_iterator.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
#include <time.h>
#include <iostream>
std::vector<std::string> getDays(time_t start, time_t end) {
std::vector<std::string> ret;
std::transform(boost::make_counting_iterator<unsigned>(start/(24*3600)),
boost::make_counting_iterator<unsigned>(end/(24*3600)),
std::back_inserter(ret),
[](unsigned day) {
return to_iso_extended_string(boost::posix_time::from_time_t(day*3600*24)).substr(0,10);
});
return ret;
}
测试了:
int main() {
const std::vector<std::string> days = getDays(0, time(NULL));
std::copy(days.begin(), days.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
什么'int's? –
这听起来像一个有趣的小问题 – Grammin
我假设他们是像Unix时间戳(从Epoch毫秒)。 – Xion