C++——时间戳转年月日时分秒格式

C语言时间戳转换示例
#include <stdio.h>  
#include <time.h>  
  
int main() {  
    // 获取当前时间(以秒为单位的时间戳)  
    time_t rawtime;  
    time(&rawtime);  
  
    // 将时间戳转换为本地时间(struct tm)  
    struct tm * timeinfo = localtime(&rawtime);  
  
    // 使用strftime函数将struct tm转换为可读的字符串格式  
    char buffer[80];  
    strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);  
  
    // 打印结果  
    printf("当前时间是: %s\n", buffer);  
  
    return 0;  
}

在这里插入图片描述

C++中,将double类型的Unix时间戳(通常是以秒为单位)转换年月日时分秒毫秒格式,你可以通过以下几个步骤: 1. **获取当前时间戳**:首先,你需要从系统获取当前的时间戳,可以使用`std::chrono::time_point_cast<std::chrono::seconds>`函数将double转换为秒级的时间点。 ```cpp #include <chrono> #include <ctime> double timestamp_in_seconds = ...; // 你的double时间戳 auto time_point = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::from_time_t(timestamp_in_seconds)); ``` 2. **计算详细信息**:然后,你可以从这个时间点中提取出年、月、日、小时、分钟、秒和毫秒。C++ `<ctime>`库提供了一些方便的函数来帮助你做这个工作。 ```cpp std::tm tm_info; std::istringstream iss(std::to_string(time_point.time_since_epoch().count())); iss >> std::get_time(&tm_info, "%Y-%m-%d %H:%M:%S"); int year = tm_info.tm_year + 1900; // 补充1900年偏移 int month = tm_info.tm_mon + 1; int day = tm_info.tm_mday; int hour = tm_info.tm_hour; int minute = tm_info.tm_min; int second = tm_info.tm_sec; int millisecond = (time_point.time_since_epoch().count() - std::chrono::seconds(tm_info.tm_hour * 3600 + tm_info.tm_min * 60 + tm_info.tm_sec).count()) * 1000; // 计算毫秒 ``` 3. **格式化字符串**:最后,你可以用这些信息构造一个格式化的字符串。 ```cpp std::ostringstream oss; oss << year << "-" << month << "-" << day << " " << hour << ":" << minute << ":" << second << "." << millisecond; std::string formatted_date = oss.str(); ``` 现在`formatted_date`变量就包含了你要的格式化日期时间字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值