C++常用基础函数整理

 一、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
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焱齿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值