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

如何用C++将带毫秒的日期时间字符串转为64位UNIX时间戳

Convert Datetime String with Milliseconds to 64-bit Unix Timestamp in C++

Got it, let's solve this problem—turning that 2013-04-12 16:00:15.041 string into a 64-bit Unix timestamp that keeps the milliseconds intact. Most quick fixes only handle second-level precision, but we need to hang onto those fractional seconds. Here are two solid approaches depending on your C++ version:

Method 1: C11/17 (Standard, No C20 Features)

This works with older compilers and uses standard library tools to parse the string, extract milliseconds, and compute the timestamp.

First, include the necessary headers:

#include <iostream>
#include <string>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <cstdint>
#include <stdexcept>

Then the core function:

int64_t datetime_to_ms_timestamp(const std::string& datetime_str) {
    std::tm tm_time = {};
    std::istringstream input_stream(datetime_str);

    // Parse the date/time up to the seconds part
    input_stream >> std::get_time(&tm_time, "%Y-%m-%d %H:%M:%S");
    if (input_stream.fail()) {
        throw std::invalid_argument("Invalid datetime format (failed to parse date/time)");
    }

    // Extract milliseconds from the fractional part
    double fractional_seconds = 0.0;
    if (input_stream.peek() == '.') {
        char dot;
        input_stream >> dot >> fractional_seconds;
        // Convert 0.041 to 41 milliseconds
        fractional_seconds *= 1000;
    }

    // Convert tm struct (local time) to a system_clock time point
    auto base_time = std::chrono::system_clock::from_time_t(std::mktime(&tm_time));

    // Add the milliseconds to the base time
    base_time += std::chrono::milliseconds(static_cast<long long>(fractional_seconds));

    // Calculate total milliseconds since Unix epoch (1970-01-01 UTC)
    auto total_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
        base_time.time_since_epoch()
    ).count();

    return static_cast<int64_t>(total_ms);
}

Key Notes for This Method:

  • std::mktime treats the std::tm struct as local time. If your input string is in UTC, you'll need to adjust for your timezone offset, or use platform-specific functions like timegm (Linux/macOS) to convert UTC directly.
  • The code handles fractional seconds by reading the part after the dot, converting it to milliseconds. It works for 1-3 digit millisecond values (common in most datetime strings).
  • We use int64_t to store the timestamp since millisecond-level timestamps easily exceed 32-bit integer limits (they hit the 32-bit max around 2038).

Method 2: C++20 (Cleaner UTC Support)

If you're using a modern compiler that supports C++20, this method is far more concise and handles UTC natively:

#include <chrono>
#include <format>
#include <string>
#include <cstdint>
#include <stdexcept>

int64_t datetime_to_ms_timestamp_utc(const std::string& datetime_str) {
    using namespace std::chrono;

    // Parse the UTC datetime string directly into a system_clock time point (millisecond precision)
    auto parse_result = parse("%Y-%m-%d %H:%M:%S.%f", datetime_str, sys_time<milliseconds>{});
    if (!parse_result) {
        throw std::invalid_argument("Failed to parse UTC datetime string");
    }

    // Return total milliseconds since epoch
    return parse_result->time_since_epoch().count();
}

Why This Is Better:

  • std::chrono::parse directly handles fractional seconds and converts the string to a UTC-based time point—no timezone guesswork.
  • Way less boilerplate code—no need to manually split out milliseconds or mess with std::tm.

Test the Code

Here's how to use either function:

int main() {
    try {
        const std::string target_datetime = "2013-04-12 16:00:15.041";
        
        // C++11/17 method (local time)
        int64_t local_timestamp = datetime_to_ms_timestamp(target_datetime);
        std::cout << "Local time timestamp (ms): " << local_timestamp << "\n";

        // C++20 method (UTC time)
        // int64_t utc_timestamp = datetime_to_ms_timestamp_utc(target_datetime);
        // std::cout << "UTC timestamp (ms): " << utc_timestamp << "\n";
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << "\n";
    }
    return 0;
}

Important Reminders:

  • Always validate the input string to avoid parsing errors—this code throws exceptions, but you could also return a boolean success flag if preferred.
  • For the C++11/17 method, if your input is UTC, make sure to adjust the timezone conversion to avoid off-by-hours errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:54:43