How to convert only the date without time to a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <chrono>
#include <iomanip> // oss

/*
    Function: dateToString
    Purpose : Convert a std::chrono::system_clock::time_point
              to a string containing ONLY the date (YYYY-MM-DD)
*/
std::string dateToString(const std::chrono::system_clock::time_point& tp) {
    // Convert to time_t (calendar time)
    std::time_t rawTime = std::chrono::system_clock::to_time_t(tp);

    // Convert to tm structure (broken-down time)
    std::tm* timeInfo = std::localtime(&rawTime);

    // Format the date into a string
    std::ostringstream oss;
    oss << std::put_time(timeInfo, "%Y-%m-%d");  // Only date

    return oss.str();
}

std::chrono::system_clock::time_point makeDate(int y, int m, int d) {
    std::tm t = {};
    t.tm_year = y - 1900;
    t.tm_mon  = m - 1;
    t.tm_mday = d;
    
    return std::chrono::system_clock::from_time_t(std::mktime(&t));
}


int main()
{
    // Get current system time
    auto now = std::chrono::system_clock::now();
    std::string dateStr = dateToString(now);
    std::cout << "Today's date is: " << dateStr << std::endl;

    auto myDate = makeDate(2025, 12, 7);
    std::string hardcodedStr = dateToString(myDate);
    std::cout << "Hard-coded date is: " << hardcodedStr << std::endl;
    
    using namespace std::chrono;

    year_month_day ymd{year{2028}, month{6}, day{21}};
    sys_days sd = ymd;
    std::cout << "C++20 date: " << dateToString(sd) << std::endl;
}



/* 
run:

Today's date is: 2026-05-30
Hard-coded date is: 2025-12-07
C++20 date: 2028-06-21

*/

 



answered 9 hours ago by avibootz

Related questions

...