【发布时间】:2015-11-19 13:45:37
【问题描述】:
我有一个获取文件的界面,文件名是内部数据有效时的时间戳。我正在按顺序处理文件并将它们提供给另一个 API,该 API 自 1970 年 1 月 1 日以来花费的时间为毫秒。
因此,我将文件名作为 YYYYMMDD_HHmmSS.sss 格式的字符串输入,并且必须将其转换为时间。我假设处理和收集发生在同一时区等,只需将字符转换为数字。
uint64_t foo::convertFileNameToTimestamp(const std::string& filename) const
{
const uint64_t yyyy = atoi(filename.substr(0,4).c_str());
const uint64_t MM = atoi(filename.substr(4,2).c_str());
const uint64_t DD = atoi(filename.substr(6,2).c_str());
const uint64_t HH = atoi(filename.substr(9,2).c_str());
const uint64_t MI = atoi(filename.substr(11,2).c_str());
const uint64_t SS = atoi(filename.substr(13,2).c_str());
const uint64_t sss = atoi(filename.substr(16,3).c_str());
// number of milliseconds in a day
const uint64_t DAY = 24 * 60 * 60 * 1000;
int MD = 0;
if (MM == 2) MD = 31; // currently feb, so add all of january's days
else if (MM == 3) MD = 31+28; // ...
else if (MM == 4) MD = 31+28+31;
else if (MM == 5) MD = 31+28+31+30;
else if (MM == 6) MD = 31+28+31+30+31;
else if (MM == 7) MD = 31+28+31+30+31+30;
else if (MM == 8) MD = 31+28+31+30+31+30+31;
else if (MM == 9) MD = 31+28+31+30+31+30+31+31;
else if (MM == 10) MD = 31+28+31+30+31+30+31+31+30;
else if (MM == 11) MD = 31+28+31+30+31+30+31+31+30+31;
else if (MM == 12) MD = 31+28+31+30+31+30+31+31+30+31+30;
// year 2000 wasn't a leap year
uint64_t YLD = ((yyyy-1970) / 4);
if (yyyy > 2000) --YLD;
uint64_t temp = sss;
temp += SS * 1000;
temp += MI * 60 * 1000;
temp += HH * 60 * 60 * 1000;
temp += (DD-1) * DAY;
temp += (MD) * DAY;
temp += (yyyy-1970) * 365 * DAY + YLD*DAY;
return temp;
}
显然,在这里重新发明轮子。似乎应该为此提供某种功能。另外..我如何考虑闰秒?处理闰日已经够烦人的了。时间戳都是 2015 年及以后的,而且永远都是,但我认为我不能盲目地添加 26 秒。最终我们将有 27 个或备份到 25 个。在之前的函数中,我已经验证了字符串的格式是否正确,文件是否存在以及所有这些爵士乐。我正在使用 VS 2010 在 Windows 8.1 编译 64 位上运行。
我查看了建议 ctime() 的 Convert Epoch Time string to Time,但它似乎没有处理构造函数中的毫秒数,甚至没有处理任何 get 方法,而且它不接受一般格式化的字符串输入。我假设我必须调用一些时间类 CTOR,它们将接受文件名字符串,然后调用一些访问器以获取自 1970 年以来的毫秒时间,包括闰秒等。
我没有使用 boost,也没有使用它的访问权限。
【问题讨论】:
-
那个
else if块太残暴了。将日期放入数据结构中,并使用MM作为开始索引循环返回它们 -
// year 2000 wasn't a leap year其实是这样。 -
您可能会发现有用的日期算法:howardhinnant.github.io/date_algorithms.html
-
@HowardHinnant 非常正确。当我检查下面的答案时发现了这一点。