Created
July 4, 2019 12:03
-
-
Save khrykin/d6e8fdbd99b772947234f8168d4b63c9 to your computer and use it in GitHub Desktop.
Get current day's duration in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctime> | |
#include <chrono> | |
#include <string> | |
#include <sstream> | |
#include <iomanip> | |
#include <iostream> | |
using Timestamp = std::time_t; | |
using DayComponents = std::tm; | |
using Duration = std::chrono::duration<double>; | |
const auto dayComponentsFromTimestamp = std::localtime; | |
const auto timestampFromDayComponents = std::mktime; | |
Timestamp startOfADayFromTimestamp(Timestamp timestamp) { | |
auto dayComponents = *dayComponentsFromTimestamp(×tamp); | |
dayComponents.tm_hour = 0; | |
dayComponents.tm_min = 0; | |
dayComponents.tm_sec = 0; | |
timestamp = timestampFromDayComponents(&dayComponents); | |
return timestamp; | |
} | |
Duration currentDayDuration() { | |
using namespace std::chrono; | |
auto clockNow = system_clock::now(); | |
auto currentTimestamp = system_clock::to_time_t(clockNow); | |
auto startOfADayTimestamp = startOfADayFromTimestamp(currentTimestamp); | |
auto clockStartOfToday = system_clock::from_time_t(startOfADayTimestamp); | |
return clockNow - clockStartOfToday; | |
} | |
int main() { | |
using namespace std::chrono; | |
auto duration = currentDayDuration(); | |
auto currentMinute = duration_cast<minutes>(duration).count(); | |
std::cout << "Current minute: " << currentMinute << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment