一、C++适应于任何内置类型数据转换的函数
函数定义如下,这里用到了模板。
template <class FromType, class ToType>
inline ToType To(const FromType& from, const ToType& init_to_value)
{
ToType to = init_to_value;
std::stringstream ss;
ss << from;
ss >> to;
return to;
}
使用如下:
To<uint64_t, std::string>(kfuin, ""); #uint64数值转换为string字串
To<std::string, uint64_t>(strkfuin,0); #string字串转换为uint64数值
To<std::string, uint32_t>(flagNum, 0); #string字串转换为uint64数值
关于格式转换也不要纠结:
C++ 数值与 string 的相互转换_Dablelv的博客专栏-CSDN博客
二、根据时间戳获取可读日期(时间)的函数
1、将秒时间戳转换成day日期
std::string GetDateStrFromStamp(time_t time)
{
struct tm tmTemp;
localtime_r(&time, &tmTemp);
char buf[32] = {0};
snprintf(buf, sizeof buf, "%4d%02d%02d", tmTemp.tm_year + 1900, tmTemp.tm_mon + 1, tmTemp.tm_mday);
return buf;
}
2、将秒时间戳转换成可读时间
std::string GetReadableStrTimeFromStamp(time_t time)
{
struct tm tmTemp;
localtime_r(&time, &tmTemp);
char buf[32] = {0};
snprintf(buf, sizeof buf, "%4d-%02d-%02d %02d:%02d:%02d", tmTemp.tm_year + 1900, tmTemp.tm_mon + 1, tmTemp.tm_mday, tmTemp.tm_hour, tmTemp.tm_min, tmTemp.tm_sec);
return buf;
}
执行效果如下:
其实没有什么东西,主要就是其中的tm这个结构:
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
#ifdef __USE_BSD
long int tm_gmtoff; /* Seconds east of UTC. */
__const char *tm_zone; /* Timezone abbreviation. */
#else
long int __tm_gmtoff; /* Seconds east of UTC. */
__const char *__tm_zone; /* Timezone abbreviation. */
#endif
};