You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++标准库获取带毫秒的当前日期时间戳?

Formatting High-Resolution Timestamp to ISO 8601 Style in C++17

Alright, let's tackle this problem step by step. Since you're working with C++17 and Clang 6, we can stick entirely to the standard library—no Boost or third-party dependencies needed. You already have std::chrono::high_resolution_clock::now() to get the time point; the trick is converting that into the YYYY-MM-DDTHH:MM:SS.ffffff format you want.

Key Steps to Remember

  • high_resolution_clock might be an alias for either system_clock or steady_clock. We need to convert it to system_clock because that's the clock tied to calendar time (which we can format into dates/times).
  • We need to split the timestamp into two parts: the full second component (formatted with std::put_time) and the microsecond fraction (padded to six digits).

Complete Code Example

Here's a reusable function that does exactly what you need:

#include <chrono>
#include <iomanip>
#include <sstream>
#include <string>
#include <ctime>

std::string format_iso8601_timestamp(const std::chrono::high_resolution_clock::time_point& tp) {
    // Convert high_resolution time point to system_clock time point (for calendar alignment)
    const auto sys_time_point = std::chrono::system_clock::from_time_t(
        std::chrono::system_clock::to_time_t(tp)
    );
    
    // Calculate the microsecond fraction (since system_clock might only track seconds)
    const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(
        tp - sys_time_point
    ).count();

    // Convert to a tm structure to extract calendar components
    const std::time_t raw_time = std::chrono::system_clock::to_time_t(tp);
    const std::tm local_time = *std::localtime(&raw_time); // Use gmtime() instead for UTC

    // Build the formatted string
    std::ostringstream oss;
    // Format date/time part using ISO 8601 without time zone
    oss << std::put_time(&local_time, "%Y-%m-%dT%H:%M:%S");
    // Append microseconds, padded to 6 digits with leading zeros
    oss << "." << std::setw(6) << std::setfill('0') << microseconds;

    return oss.str();
}

// Example usage
int main() {
    const auto now = std::chrono::high_resolution_clock::now();
    const std::string timestamp = format_iso8601_timestamp(now);
    std::cout << timestamp << "\n";
    return 0;
}

How It Works

  1. Clock Conversion: We convert the high_resolution_clock time point to system_clock to align it with calendar time. This lets us extract the year, month, day, hour, minute, and second values.
  2. Microsecond Calculation: By subtracting the aligned system_clock time point from the original high-resolution time point, we get the fraction of a second, which we cast to microseconds to get the six-digit value we need.
  3. Formatting: std::put_time handles the date and time string using the format specifier %Y-%m-%dT%H:%M:%S (matching your desired structure). We then append the microseconds, using std::setw(6) and std::setfill('0') to ensure we always have six digits (even if the microsecond value is less than 100000).

Quick Notes

  • If you need UTC time instead of local time, replace std::localtime(&raw_time) with std::gmtime(&raw_time).
  • Clang 6 fully supports the C++17 features used here—std::chrono utilities and std::put_time are all available and work as expected.

内容的提问来源于stack exchange,提问作者425nesp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:39:04