C++版实用时间戳类(Timestamp)

1、直接上干货!

        新建文件timestamp.h,内容如下:

#pragma once
/***************************************************
*	created:				2024.11.17
*	filename: 			
*	file path:			
*	author:				YZS
*
*	purpose:				 时间戳类
*****************************************************
*	Release Note  :****************************************************/
#include <string>
#include <stdint.h>#define INVALID_TIMESTAMP (0)namespace system{/** A system independent time type, it holds the the number of 100-nanosecond intervals since January 1, 1601 (UTC).* \sa system::getCurrentTime, system::timeDifference, INVALID_TIMESTAMP, TTimeParts*/typedef uint64_t TTimeStamp;/** The parts of a date/time (it's like the standard 'tm' but with fractions of seconds).* \sa TTimeStamp, timestampToParts, buildTimestampFromParts*/struct TTimeParts{uint16_t	year;	/** The year */uint8_t		month;  /** Month (1-12) */uint8_t		day;    /** Day (1-31) */uint8_t		hour;   /** Hour (0-23) */uint8_t		minute; /** Minute (0-59) */double		second; /** Seconds (0.0000-59.9999) */uint8_t		day_of_week; /** Day of week (1:Sunday, 7:Saturday) */int			daylight_saving;};/** Builds a timestamp from the parts (Parts are in local time)* \sa timestampToParts, buildTimestampFromParts*/system::TTimeStamp  buildTimestampFromPartsLocalTime(const system::TTimeParts& p);/** Gets the individual parts of a date/time (days, hours, minutes, seconds) - UTC time or local time* \sa buildTimestampFromParts*/void  timestampToParts(TTimeStamp t, TTimeParts& p, bool localTime = false);/** Returns the current (UTC) system time.* \sa now,getCurrentLocalTime*/system::TTimeStamp   getCurrentTime();/** A shortcut for system::getCurrentTime* \sa getCurrentTime, getCurrentLocalTime*/inline system::TTimeStamp now() {return getCurrentTime();}/** Returns the current (local) time.* \sa now,getCurrentTime*/system::TTimeStamp    getCurrentLocalTime();/** Transform from standard "time_t" (actually a double number, it can contain fractions of seconds) to TTimeStamp.* \sa timestampTotime_t*/system::TTimeStamp   time_tToTimestamp(const double t);/** Transform from standard "time_t" to TTimeStamp.* \sa timestampTotime_t*/system::TTimeStamp   time_tToTimestamp(const time_t& t);/** Transform from TTimeStamp to standard "time_t" (actually a double number, it can contain fractions of seconds).* \sa time_tToTimestamp, secondsToTimestamp*/double  timestampTotime_t(const system::TTimeStamp  t);/** Transform from TTimeStamp to standard "time_t" (actually a double number, it can contain fractions of seconds).* This function is just an (inline) alias of timestampTotime_t(), with a more significant name.* \sa time_tToTimestamp, secondsToTimestamp*/inline double timestampToDouble(const system::TTimeStamp  t) { return timestampTotime_t(t); }double  timeDifference(const system::TTimeStamp t_first, const system::TTimeStamp t_later); //!< Returns the time difference from t1 to t2 (positive if t2 is posterior to t1), in seconds \sa secondsToTimestamp/** Returns the current time, as a `double` (fractional version of time_t) instead of a `TTimeStamp`.* \sa now(), timestampTotime_t() */inline double now_double() {return system::timestampTotime_t(system::getCurrentTime());}system::TTimeStamp  timestampAdd(const system::TTimeStamp tim, const double num_seconds); //!< Shifts a timestamp the given amount of seconds (>0: forwards in time, <0: backwards) \sa secondsToTimestamp/** Transform a time interval (in seconds) into TTimeStamp (e.g. which can be added to an existing valid timestamp)* \sa timeDifference*/system::TTimeStamp  secondsToTimestamp(const double nSeconds);/** Returns a formated string with the given time difference (passed as the number of seconds), as a string [H]H:MM:SS.MILISECS* \sa unitsFormat*/std::wstring  formatTimeInterval(const double timeSeconds);/** Convert a timestamp into this textual form (UTC time): YEAR/MONTH/DAY,HH:MM:SS.MMM* \sa dateTimeLocalToString*/std::wstring   dateTimeToString(const system::TTimeStamp t);/** Convert a timestamp into this textual form (in local time): YEAR/MONTH/DAY,HH:MM:SS.MMM* \sa dateTimeToString*/std::wstring   dateTimeLocalToString(const system::TTimeStamp t);/** Convert a timestamp into this textual form: YEAR/MONTH/DAY*/std::wstring   dateToString(const system::TTimeStamp t);/** Returns the number of seconds ellapsed from midnight in the given timestamp*/double   extractDayTimeFromTimestamp(const system::TTimeStamp t);/** Convert a timestamp into this textual form (UTC): HH:MM:SS.MMMMMM*/std::wstring   timeToString(const system::TTimeStamp t);/** Convert a timestamp into this textual form (in local time): HH:MM:SS.MMMMMM*/std::wstring   timeLocalToString(const system::TTimeStamp t, unsigned int secondFractionDigits = 6);/** This function implements time interval formatting: Given a time in seconds, it will return a string describing the interval with the most appropriate unit.* E.g.: 1.23 year, 3.50 days, 9.3 hours, 5.3 minutes, 3.34 sec, 178.1 ms,  87.1 us.* \sa unitsFormat*/std::wstring  intervalFormat(const double seconds);} // End of namespace

        timestamp.cpp文件内容如下:

#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <iostream>#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#include <process.h>
#include <tlhelp32.h>
#include <sys/utime.h>
#include <io.h>
#include <direct.h>
#else
#include <pthread.h>
#include <termios.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <utime.h>
#include <errno.h>
#endifusing namespace system;
using namespace std;system::TTimeStamp  system::time_tToTimestamp(const time_t& t)
{return uint64_t(t) * UINT64_C(10000000) + UINT64_C(116444736) * UINT64_C(1000000000);
}system::TTimeStamp  system::time_tToTimestamp(const double t)
{return uint64_t(t * 10000000.0) + UINT64_C(116444736) * UINT64_C(1000000000);
}double system::timestampTotime_t(const system::TTimeStamp t)
{return double(t - UINT64_C(116444736) * UINT64_C(1000000000)) / 10000000.0;
}std::wstring format(const wchar_t* fmt, ...)
{if (!fmt) return std::wstring();int   result = -1, length = 2048;std::wstring buffer;while (result == -1){buffer.resize(length);va_list args;  // This must be done WITHIN the loopva_start(args, fmt);result = vswprintf_s(&buffer[0], length, fmt, args);va_end(args);// Truncated?if (result >= length) result = -1;length *= 2;// Ok?if (result >= 0) {buffer.resize(result);}}return buffer;
}system::TTimeStamp  system::getCurrentTime()
{
#ifdef _WIN32FILETIME		t;GetSystemTimeAsFileTime(&t);return (((uint64_t)t.dwHighDateTime) << 32) | ((uint64_t)t.dwLowDateTime);
#elsetimespec  tim;clock_gettime(CLOCK_REALTIME, &tim);return time_tToTimestamp(tim.tv_sec) + tim.tv_nsec / 100;
#endif
}void system::timestampToParts(TTimeStamp t, TTimeParts& p, bool localTime)
{const double T = system::timestampTotime_t(t);double sec_frac = T - floor(T);assert(sec_frac < 1.0);const time_t tt = time_t(T);struct tm* parts = localTime ? localtime(&tt) : gmtime(&tt);//ASSERTMSG_(parts, "Malformed timestamp");p.year = parts->tm_year + 1900;p.month = parts->tm_mon + 1;p.day = parts->tm_mday;p.day_of_week = parts->tm_wday + 1;p.daylight_saving = parts->tm_isdst;p.hour = parts->tm_hour;p.minute = parts->tm_min;p.second = parts->tm_sec + sec_frac;
}TTimeStamp system::buildTimestampFromPartsLocalTime(const TTimeParts& p)
{struct tm parts;parts.tm_year = p.year - 1900;parts.tm_mon = p.month - 1;parts.tm_mday = p.day;parts.tm_wday = p.day_of_week - 1;parts.tm_isdst = p.daylight_saving;parts.tm_hour = p.hour;parts.tm_min = p.minute;parts.tm_sec = int(p.second);double sec_frac = p.second - parts.tm_sec;time_t  tt = mktime(&parts);return system::time_tToTimestamp(double(tt) + sec_frac);
}system::TTimeStamp  system::getCurrentLocalTime()
{
#ifdef _WIN32FILETIME		tt, t;GetSystemTimeAsFileTime(&tt);FileTimeToLocalFileTime(&tt, &t);return (((uint64_t)t.dwHighDateTime) << 32) | ((uint64_t)t.dwLowDateTime);
#elsetimespec  tim;clock_gettime(CLOCK_REALTIME, &tim);time_t  tt;struct tm* timeinfo;time(&tt);timeinfo = localtime(&tt);return time_tToTimestamp(mktime(timeinfo)) + tim.tv_nsec / 100;
#endif
}system::TTimeStamp system::timestampAdd(const system::TTimeStamp tim, const double num_seconds)
{return static_cast<system::TTimeStamp>(tim + static_cast<int64_t>(num_seconds * 10000000.0));
}double system::timeDifference(const system::TTimeStamp t1, const system::TTimeStamp t2)
{//PPF_STARTassert(t1 != INVALID_TIMESTAMP);assert(t2 != INVALID_TIMESTAMP);return (int64_t(t2) - int64_t(t1)) / 10000000.0;//PPF_END
}system::TTimeStamp system::secondsToTimestamp(const double nSeconds)
{return (system::TTimeStamp)(nSeconds * 10000000.0);
}std::wstring system::formatTimeInterval(const double t)
{double timeSeconds = (t < 0) ? (-t) : t;unsigned int nHours = (unsigned int)timeSeconds / 3600;unsigned int nMins = ((unsigned int)timeSeconds % 3600) / 60;unsigned int nSecs = (unsigned int)timeSeconds % 60;unsigned int milSecs = (unsigned int)(1000 * (timeSeconds - floor(timeSeconds)));return format(L"%02u:%02u:%02u.%03u",nHours,nMins,nSecs,milSecs);
}/*---------------------------------------------------------------Convert a timestamp into this textual form: YEAR/MONTH/DAY,HH:MM:SS.MMM---------------------------------------------------------------*/
std::wstring  system::dateTimeToString(const system::TTimeStamp t)
{if (t == INVALID_TIMESTAMP) return std::wstring(L"INVALID_TIMESTAMP");uint64_t        tmp = (t - ((uint64_t)116444736 * 1000000000));time_t          auxTime = tmp / (uint64_t)10000000;unsigned int	secFractions = (unsigned int)(1000000 * (tmp % 10000000) / 10000000.0);tm* ptm = gmtime(&auxTime);if (!ptm)return std::wstring(L"(Malformed timestamp)");return format(L"%u/%02u/%02u,%02u:%02u:%02u.%06u",1900 + ptm->tm_year,ptm->tm_mon + 1,ptm->tm_mday,ptm->tm_hour,ptm->tm_min,(unsigned int)ptm->tm_sec,secFractions);
}/*---------------------------------------------------------------Convert a timestamp into this textual form (in local time):YEAR/MONTH/DAY,HH:MM:SS.MMM---------------------------------------------------------------*/
std::wstring  system::dateTimeLocalToString(const system::TTimeStamp t)
{if (t == INVALID_TIMESTAMP) return std::wstring(L"INVALID_TIMESTAMP");uint64_t        tmp = (t - ((uint64_t)116444736 * 1000000000));time_t          auxTime = tmp / (uint64_t)10000000;unsigned int	secFractions = (unsigned int)(1000000 * (tmp % 10000000) / 10000000.0);tm* ptm = localtime(&auxTime);if (!ptm) return L"(Malformed timestamp)";return format(L"%u/%02u/%02u,%02u:%02u:%02u.%06u",1900 + ptm->tm_year,ptm->tm_mon + 1,ptm->tm_mday,ptm->tm_hour,ptm->tm_min,(unsigned int)ptm->tm_sec,secFractions);
}double  system::extractDayTimeFromTimestamp(const system::TTimeStamp t)
{//PPF_STARTassert(t != INVALID_TIMESTAMP);#ifdef _WIN32SYSTEMTIME		sysT;FileTimeToSystemTime((FILETIME*)&t, &sysT);return sysT.wHour * 3600.0 + sysT.wMinute * 60.0 + sysT.wSecond + sysT.wMilliseconds * 0.001;
#elsetime_t      auxTime = (t - ((uint64_t)116444736 * 1000000000)) / (uint64_t)10000000;tm* ptm = gmtime(&auxTime);ASSERTMSG_(ptm, "Malformed timestamp");return ptm->tm_hour * 3600.0 + ptm->tm_min * 60.0 + ptm->tm_sec;
#endif//PPF_END
}/*---------------------------------------------------------------Convert a timestamp into this textual form: HH:MM:SS.MMM---------------------------------------------------------------*/
std::wstring  system::timeLocalToString(const system::TTimeStamp t, unsigned int secondFractionDigits)
{if (t == INVALID_TIMESTAMP) return std::wstring(L"INVALID_TIMESTAMP");uint64_t        tmp = (t - ((uint64_t)116444736 * 1000000000));const time_t          auxTime = tmp / (uint64_t)10000000;const tm* ptm = localtime(&auxTime);unsigned int	secFractions = (unsigned int)(1000000 * (tmp % 10000000) / 10000000.0);// We start with 10^{-6} second units: reduce if requested by user:const unsigned int user_secondFractionDigits = secondFractionDigits;while (secondFractionDigits++ < 6)secFractions = secFractions / 10;return format(L"%02u:%02u:%02u.%0*u",ptm->tm_hour,ptm->tm_min,(unsigned int)ptm->tm_sec,user_secondFractionDigits,secFractions);
}/*---------------------------------------------------------------Convert a timestamp into this textual form: HH:MM:SS.MMM---------------------------------------------------------------*/
std::wstring  system::timeToString(const system::TTimeStamp t)
{if (t == INVALID_TIMESTAMP) return std::wstring(L"INVALID_TIMESTAMP");uint64_t        tmp = (t - ((uint64_t)116444736 * 1000000000));time_t          auxTime = tmp / (uint64_t)10000000;unsigned int	secFractions = (unsigned int)(1000000 * (tmp % 10000000) / 10000000.0);tm* ptm = gmtime(&auxTime);if (!ptm)return std::wstring(L"(Malformed timestamp)");return format(L"%02u:%02u:%02u.%06u",ptm->tm_hour,ptm->tm_min,(unsigned int)ptm->tm_sec,secFractions);
}/*---------------------------------------------------------------Convert a timestamp into this textual form: YEAR/MONTH/DAY---------------------------------------------------------------*/
std::wstring  system::dateToString(const system::TTimeStamp t)
{if (t == INVALID_TIMESTAMP) return std::wstring(L"INVALID_TIMESTAMP");uint64_t        tmp = (t - ((uint64_t)116444736 * 1000000000));time_t          auxTime = tmp / (uint64_t)10000000;tm* ptm = gmtime(&auxTime);if (!ptm)return std::wstring(L"(Malformed timestamp)");return format(L"%u/%02u/%02u",1900 + ptm->tm_year,ptm->tm_mon + 1,ptm->tm_mday);
}/** This function implements time interval formatting: Given a time in seconds, it will return a string describing the interval with the most appropriate unit.* E.g.: 1.23 year, 3.50 days, 9.3 hours, 5.3 minutes, 3.34 sec, 178.1 ms,  87.1 us.*/
std::wstring
system::intervalFormat(const double seconds)
{if (seconds >= 365 * 24 * 3600)return format(L"%.2f years", seconds / (365 * 24 * 3600));else if (seconds >= 24 * 3600)return format(L"%.2f days", seconds / (24 * 3600));else if (seconds >= 3600)return format(L"%.2f hours", seconds / 3600);else if (seconds >= 60)return format(L"%.2f minutes", seconds / 60);else if (seconds >= 1)return format(L"%.2f sec", seconds);else if (seconds >= 1e-3)return format(L"%.2f ms", seconds * 1e3);else if (seconds >= 1e-6)return format(L"%.2f us", seconds * 1e6);else	return format(L"%.2f ns", seconds * 1e9);
}

        直接愉快的加入到项目使用!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/493059.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DB-GPT 智谱在线模型配置

LLM_MODELzhipu_proxyllm PROXY_SERVER_URLhttps://open.bigmodel.cn/api/paas/v4/chat/completions ZHIPU_MODEL_VERSIONglm-4 ZHIPU_PROXY_API_KEY70e8ec7113882ff5478fcecaa47522479.ExY2LyjcvWmqrTAf

【GCC】2015: draft-alvestrand-rmcat-congestion-03 机器翻译

腾讯云的一个分析,明显是看了这个论文和草案的 : 最新的是应该是这个 A Google Congestion Control Algorithm for Real-Time Communication draft-ietf-rmcat-gcc-02 下面的这个应该过期了: draft-alvestrand-rmcat-congestion-03

python:用 sklearn 构建线性回归模型,并评价

编写 test_sklearn_6.py 如下 # -*- coding: utf-8 -*- """ 使用 sklearn 估计器构建线性回归模型 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import rcParamsfrom sklearn import dataset…

系统思考—战略共识

当企业不增长的时候&#xff0c;是忙着救火&#xff0c;还是在真正解决问题&#xff1f; 最近遇到很多领导者&#xff0c;把精力放在“管理”上&#xff0c;希望通过抓细节提升效率&#xff0c;解决经营问题。结果呢&#xff1f;全公司上上下下忙成了一团乱麻&#xff0c;但不…

web3跨链桥协议-Nomad

项目介绍 Nomad是一个乐观跨链互操作协议。通过Nomad协议&#xff0c;Dapp能够在不同区块链间发送数据&#xff08;包括rollups&#xff09;&#xff0c;Dapp通过Nomad的合约和链下的代理对跨链数据、消息进行验证、传输。其安全通过乐观验证机制和欺诈证明制约验证者实现&…

微信小程序实现画板画布自由绘制、选择画笔粗细及颜色、记录撤回、画板板擦、清空、写字板、导出绘图、canvas,开箱即用

目录 画板创建canvas绘制及渲染画笔粗细功能实现画笔颜色选择画笔痕迹撤回、板擦、画布清空canvas解析微信小程序中 canvas 的应用场景canvas 与 2D 上下文、webgl 上下文的关系图像的加载与绘制说明代码说明画板创建 canvas绘制及渲染 在wxml添加对应的canvas标签代码,并在j…

网站灰度发布?Tomcat的8005、8009、8080三个端口的作用什么是CDNLVS、Nginx和Haproxy的优缺点服务器无法开机时

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c; 忍不住分享一下给大家。点击跳转到网站 学习总结 1、掌握 JAVA入门到进阶知识(持续写作中……&#xff09; 2、学会Oracle数据库入门到入土用法(创作中……&#xff09; 3、手把…

解锁BL后的K40降级

1 下载刷机工具 https://miuiver.com/miflash/ 2、下载刷机包 https://xiaomirom.com/series/ 下载ROM包&#xff0c;12.0.8比较好 3 打开第一步下载的刷机工具 打开首次安装驱动&#xff0c; 接下来先选择个重要的东西&#xff0c;如果不想重新上BL那就选择全部删除…

蓝桥杯刷题——day8

蓝桥杯刷题——day8 题目一题干解题思路代码 题目二题干解题思路代码 题目一 题干 N 架飞机准备降落到某个只有一条跑道的机场。其中第i架飞机在 Ti时刻到达机场上空&#xff0c;到达时它的剩余油料还可以继续盘旋 Di个单位时间&#xff0c;即它最早可以于 Ti时刻开始降落&am…

redis数据类型:list

list 的相关命令配合使用的应用场景&#xff1a; 栈和队列&#xff1a;插入和弹出命令的配合&#xff0c;亦可实现栈和队列的功能 实现哪种数据结构&#xff0c;取决于插入和弹出命令的配合&#xff0c;如左插右出或右插左出&#xff1a;这两种种方式实现先进先出的数据结构&a…

IDEA中解决Edit Configurations中没有tomcat Server选项的问题

今天使用IDEA2024专业版的时候,发现Edit Configurations里面没有tomcat Server,最终找到解决方案。 一、解决办法 1、打开Settings 2、搜索tomcat插件 搜索tomcat插件之后,找到tomcat 发现tomcat插件处于未勾选状态,然后我们将其勾选保存即可。 二、结果展示 最后,再次编…

复习打卡大数据篇——Hadoop HDFS 02

目录 1. HDFS辅助工具 2. namenode安全模式 1. HDFS辅助工具 跨集群数据拷贝 当我们需要跨集群进行文件数据的拷贝时可以用&#xff1a; hadoop distcp 集群1的某个文件路径 要拷贝到集群2的地址路径 文件归档工具archive 由于HDFS的块的数量取决于文件的大小和数量&…

Mamba安装环境和使用,anaconda环境打包

什么是mamba Mamba是一个极速版本的conda&#xff0c;它是conda的C重新实现&#xff0c;使用多线程并行处理来加速包和依赖项的下载。 Mamba旨在提高安装、更新和卸载Python包的速度&#xff0c;同时保持与conda相同的兼容性和命令行接口。 Mamba的核心部分使用C实现&#xff…

Sigrity System Explorer Snip Via Pattern From Layout模式从其它设计中截取过孔模型和仿真分析操作指导

Sigrity System Explorer Snip Via Pattern From Layout模式从其它设计中截取过孔模型和仿真分析操作指导 Sigrity System Explorer Snip Via Pattern From Layout模式支持从其它设计中截取过孔模型用于仿真分析,同样以差分模板为例 具体操作如下 双击打开System Explorer软件…

顺序表的操作

注意位序和数组下标的关系 插入&#xff1a; 插入的时间复杂度&#xff1a; 最深层语句&#xff1a; 最好情况 最坏情况 平均情况 删除&#xff1a; 查找&#xff1a;

以腾讯混元模型为例,在管理平台上集成一个智能助手

背景 前几天&#xff0c;公司的同事们一起吃了个饭&#xff0c;餐桌上大家聊到大模型的落地场景。我个人在去年已经利用百度千帆平台写过案例&#xff0c;并发过博客&#xff08;传送门&#x1f449;&#xff1a;利用文心千帆打造一个属于自己的小师爷&#xff09;&#xff0c…

计算机基础 试题

建议做的时候复制粘贴,全部颜色改为黑色,做完了可以看博客对答案。 一、单项选择题(本大题共25小题,每小题2分,共50分〉 1.计算机内部采用二进制数表示信息,为了便于书写,常用十六进制数表示。一个二进制数0010011010110用十六进制数表示为 A.9A6 B.26B C.4D6 D.…

[机器学习]XGBoost(3)——确定树的结构

XGBoost的目标函数详见[机器学习]XGBoost&#xff08;2&#xff09;——目标函数&#xff08;公式详解&#xff09; 确定树的结构 之前在关于目标函数的计算中&#xff0c;均假设树的结构是确定的&#xff0c;但实际上&#xff0c;当划分条件不同时&#xff0c;叶子节点包含的…

【AI驱动的数据结构:包装类的艺术与科学】

&#x1f308;个人主页: Aileen_0v0 &#x1f525;热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法 ​&#x1f4ab;个人格言:“没有罗马,那就自己创造罗马~” 文章目录 包装类装箱和拆箱阿里巴巴面试题 包装类 在Java中基本数据类型不是继承来自Object&#xff0c;为了…

探索Moticon智能传感器鞋垫OpenGo的功能与优势

Moticon智能传感器鞋垫OpenGo是一款专为运动科学和临床研究设计的先进工具。它通过13枚压力传感器、1枚3D加速器和1枚温度传感器&#xff0c;实时监测脚部的压力分布和步态变化。用户可以通过配套的Beaker应用&#xff0c;将这些数据以图表形式呈现&#xff0c;便于分析和理解。…