【发布时间】:2019-08-17 11:18:08
【问题描述】:
我使用 Howard Hinnants date.h 库编写了以下代码,以计算当前时间一年中的小数天。我想知道是否有更短的方法可以做到这一点,因为我的代码感觉像是std::chrono 和date 调用的过度杀伤力。我可以直接计算自年初以来的小数天数(以微秒精度)并避免我的两步法吗?
#include <iostream>
#include <chrono>
#include "date.h"
int main()
{
// Get actual time.
auto now = std::chrono::system_clock::now();
// Get the number of days since start of the year.
auto ymd = date::year_month_day( date::floor<date::days>(now) );
auto ymd_ref = date::year{ymd.year()}/1/1;
int days = (date::sys_days{ymd} - date::sys_days{ymd_ref}).count();
// Get the fractional number of seconds of the day.
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(now - date::floor<date::days>(now));
double seconds_since_midnight = 1e-6*microseconds.count();
// Get fractional day number.
std::cout << "Fractional day of the year: " << days + seconds_since_midnight / 86400. << std::endl;
return 0;
}
【问题讨论】:
-
代码是否按预期工作?那么您可能会在Code Review Stack Exchange 上得到更好的答案。
-
@MikeBorkland。如何使用
date和chrono跳过两步法对我来说似乎是一个有效的问题。我需要改写吗?
标签: c++ date datetime time chrono