C++ time_t与string的互相转换

时间格式:"YYYY-MM-DD 11:11:11"

1.string转time_t

time_t StringToDatetime(std::string str)
{
    char *cha = (char*)str.data();             // 将string转换成char*。
    tm tm_;                                    // 定义tm结构体。
    int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。
    sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。
    tm_.tm_year = year - 1900;                 // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
    tm_.tm_mon = month - 1;                    // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
    tm_.tm_mday = day;                         // 日。
    tm_.tm_hour = hour;                        // 时。
    tm_.tm_min = minute;                       // 分。
    tm_.tm_sec = second;                       // 秒。
    tm_.tm_isdst = 0;                          // 非夏令时。
    time_t t_ = mktime(&tm_);                  // 将tm结构体转换成time_t格式。
    return t_;                                 // 返回值。
}

2.time_t转string

(1)
    time_t t=std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::stringstream ss;
    ss<<std::put_time(std::localtime(&t),"%F %X");
    ss.str();
(2)
    size_t strftime (char* ptr, size_t maxsize, const char* format,
                 const struct tm* timeptr );
    ptr:存储转换结果
    maxsize:复制到ptr的最大字符数,包括结束符'\0'
    format:转换格式,类似printf,可加入其他需要复制过去的字符
    timeptr:时间
    char buf[20];
    tm* local_time = std::localtime(&t);
    strftime(buf,sizeof(buf),"%F %X",local_time);

参考:

https://www.cnblogs.com/renjiashuo/p/6913668.html

https://www.cnblogs.com/qicosmos/p/3642712.html

http://www.cplusplus.com/reference/ctime/strftime/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值