首页 > 编程语言 >C++数据格式化4 - 格式化时间戳

C++数据格式化4 - 格式化时间戳

时间:2024-06-18 23:43:08浏览次数:14  
标签:std 格式化 string timestamp C++ local time include 数据

1. 关键词

C++ 数据格式化 字符串处理 std::string 时间戳 跨平台

2. strfmt.h

#pragma once

#include <string>
#include <cstdint>
#include <sstream>
#include <iomanip>
#include "timeutil.h"

namespace cutl
{
    /**
     * @brief Format a timestamp to a human-readable string with a given format.
     *
     * @param second the timestamp in seconds.
     * @param local whether to use local time or UTC time, default is local time.
     * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time.
     * @param fmt the format of the formatted string. useage like std::put_time, see https://en.cppreference.com/w/cpp/io/manip/put_time
     * @return std::string the formatted string.
     */
    std::string fmt_timestamp(uint64_t second, bool local, const std::string &fmt);
    /**
     * @brief Format a timestamp to a human-readable string.
     *
     * @param second the timestamp in seconds.
     * @param local whether to use local time or UTC time, default is local time.
     * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time.
     * @return std::string the formatted string.
     */
    std::string fmt_timestamp_s(uint64_t second, bool local = true);
    /**
     * @brief Format a timestamp to a human-readable string.
     *
     * @param ms the timestamp in milliseconds.
     * @param local whether to use local time or UTC time, default is local time.
     * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time.
     * @return std::string the formatted string.
     */
    std::string fmt_timestamp_ms(uint64_t ms, bool local = true);
    /**
     * @brief Format a timestamp to a human-readable string.
     *
     * @param us the timestamp in microseconds.
     * @param local whether to use local time or UTC time, default is local time.
     * If local is true, the function will format the timestamp to local time, otherwise, it will format the timestamp to UTC time.
     * @return std::string the formatted string.
     */
    std::string fmt_timestamp_us(uint64_t us, bool local = true);
} // namespace cutl

3. strfmt.cpp

#include <sstream>
#include <iomanip>
#include <bitset>
#include "strfmt.h"

namespace cutl
{
    // https://blog.csdn.net/u010087712/article/details/50731222
    std::string fmt_timestamp(uint64_t second, bool local, const std::string &fmt)
    {
        std::time_t t(second);
        struct tm datetime;
        if (local)
        {
            datetime = localtime_security(t);
        }
        else
        {
            datetime = gmtime_security(t);
        }

        std::stringstream ss;
        ss << std::put_time(&datetime, fmt.c_str());
        return ss.str();
    }

    // 格式化时间戳,second单位:秒
    std::string fmt_timestamp_by_unit(uint64_t t, timeunit unit, bool local)
    {
        uint64_t s = 0;
        std::string extension;
        switch (unit)
        {
        case timeunit::s:
            s = t;
            break;
        case timeunit::ms:
        {
            s = t / THOUSAND;
            auto ms = t % THOUSAND;
            extension += "." + fmt_uint(ms, 3);
        }
        break;
        case timeunit::us:
        {
            s = t / MILLION;
            auto us = t % MILLION;
            extension += "." + fmt_uint(us, 6);
        }
        break;
        default:
            break;
        }

        std::string fmt("%Y-%m-%d %H:%M:%S");
        auto time_str = fmt_timestamp(s, local, fmt);
        time_str += extension;
        return time_str;
    }

    std::string fmt_timestamp_s(uint64_t t, bool local)
    {
        return fmt_timestamp_by_unit(t, timeunit::s, local);
    }

    std::string fmt_timestamp_ms(uint64_t t, bool local)
    {
        return fmt_timestamp_by_unit(t, timeunit::ms, local);
    }

    std::string fmt_timestamp_us(uint64_t t, bool local)
    {
        return fmt_timestamp_by_unit(t, timeunit::us, local);
    }
} // namespace cutl

4. 测试代码

#include "common.hpp"
#include "strfmt.h"

void TestFormatTimestamp()
{
    PrintSubTitle("TestFormatTimestamp");
    // timestamp
    auto curTimeS = cutl::timestamp(cutl::timeunit::s);
    auto curTimeMS = cutl::timestamp(cutl::timeunit::ms);
    auto curTimeUS = cutl::timestamp(cutl::timeunit::us);
    std::cout << "current datetime s: " << cutl::fmt_timestamp_s(curTimeS) << std::endl;
    std::cout << "current datetime s in UTC: " << cutl::fmt_timestamp(curTimeS, false, "%Y/%m/%d %H:%M:%S") << std::endl;
    std::cout << "current datetime ms: " << cutl::fmt_timestamp_ms(curTimeMS) << std::endl;
    std::cout << "current datetime ms in UTC: " << cutl::fmt_timestamp_ms(curTimeMS, false) << std::endl;
    std::cout << "current datetime us: " << cutl::fmt_timestamp_us(curTimeUS) << std::endl;
}

5. 运行结果

----------------------------------------TestFormatTimestamp-----------------------------------------
current datetime s: 2024-06-18 23:22:46
current datetime s in UTC: 2024/06/18 15:22:46
current datetime ms: 2024-06-18 23:22:46.363
current datetime ms in UTC: 2024-06-18 15:22:46.363
current datetime us: 2024-06-18 23:22:46.363835

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

标签:std,格式化,string,timestamp,C++,local,time,include,数据
From: https://www.cnblogs.com/luoweifu/p/18255425

相关文章

  • 带注意力的LSTM翻译模型:在数据流动和维度变化中分析原理和核心代码
    同步发布于公众号:依古比古很无聊前言本文以CS224n课程中assignment4的代码和数据作为基础,探讨基于注意力的LSTM机器翻译模型。笔者认为,只有摸清了一个模型从输入到输出过程中的数据维度变化及其原因才是真正掌握了一个模型的结构,所以本文从数据流动及维度变化的角度出发对......
  • GBASE8s数据库关于锁的认识和检查监控
    1.锁的概念1.1.gbase8s的常规锁gbase8s数据库的锁分为两种:共享锁和排他锁共享锁:顾名思义,共享锁就是可以同时由多个用户同时获取到的锁资源一个数据(行、页、表)被加上共享锁,则同时也可以被其他用户或者session添加共享锁,但是数据加上共享锁后,不能被更新锁的添加不是单独添......
  • C++
    求一个三位数题目描述求这样一个三位数,该三位数等于其每位数字的阶乘之和。即abc=a!+b!+c!(n!表示n的阶乘)输入无输出输出这个数亲密数对题目描述键盘输入N,N在2至2000之间,求2至N中的亲密数对,就是A的因子和等于B,B的因子和等于A,且A≠B。如48......
  • 实训日记十:Python文本挖掘数据分析-part1
    目录数据分析流程项目背景&产品架构数据说明分析流程加载数据清洗数据-驱虫市场潜力分析整体市场-驱虫市场的潜力分析数据分析流程每个环节都有具体的要求,例如需求文档要求包含:目的,分析思路,预期效果业务部门出问题和需求,以及对算法&数据部门输出报告的理解和......
  • C# 数据导出成Excel的流
    导出的帮助类publicclassExcelHelper{///<summary>///将给定的模型列表转换为Excel内存流,第一行和第二行是居中对齐加粗的///</summary>///<typeparamname="T">模型类型</typeparam>///<paramname="models&qu......
  • C++数据格式化2 - 将文件大小转换为人类易读的格式
    1.关键词2.strfmt.h3.strfmt.cpp4.测试代码5.运行结果6.源码地址1.关键词C++数据格式化字符串处理std::string文件大小跨平台2.strfmt.h#pragmaonce#include<string>#include<cstdint>#include<sstream>#include<iomanip>namespacecutl{......
  • 数据库常见 SQL 语句及语法
    数据库操作创建数据库语法CREATEDATABASEdatabase_name;删除数据库语法DROPDATABASEdatabase_name;选择数据库语法USEdatabase_name;表操作创建表语法CREATETABLEtable_name(column1(字段)datatype(数据类型)constraints(约束条件),column2d......
  • 开始预习数据库第四天下
    你怎么知道我马上要考的数据库(5)开始时间 2024-06-18 20:21:58结束时间 2024-06-18 22:43:55前言:睡醒了假设某大型航空公司数据库,其关系模式(下划线代表主码)有:航班表(航班号,起点,终点,机型,价格,折扣)乘客表(身份证号,姓名,性别,年龄,会员等级)订单表(航班号,身份证号,日期,座位......
  • Arduino实现温湿度传感器以及数据上传到云(乐维互联)
    0准备材料0.1ESP-01S引脚及定义官方定义:序号pin功能1GND地线2IO0/GPIO0工作模式选择:①悬空:FlashBoot,工作模式②下拉:UARTDownLoad下载模式3IO2/GPIO2通用IO4RX/RXD数据接收端5TX/TXD谁发送端63V3/VCC3.3V,模块供电7RST1)外......
  • C++数据格式化1 - uint转换成字符串 & double转换成字符串
    1.关键词2.strfmt.h3.strfmt.cpp4.测试代码5.运行结果6.源码地址1.关键词C++数据格式化字符串处理std::stringintdouble跨平台2.strfmt.h#pragmaonce#include<string>#include<cstdint>#include<sstream>#include<iomanip>namespacecutl{......