【C/C++业务】UNIX时间戳与正常时间相互转换

正常时间转UNIX时间 与 UNIX时间转正常时间

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;

//str : 20201030
int time2unix(string str)
{
    struct tm time;
    time_t t;
    if (str.length() != 8)
        return 0;
    time.tm_year = atoi(str.substr(0, 4).c_str()) - 1900; /* 年份修正 */
    time.tm_mon = atoi(str.substr(4, 2).c_str()) - 1;     /* 月份修正 */
    time.tm_mday = atoi(str.substr(6, 2).c_str());
    time.tm_hour = 0;
    time.tm_min = 0;
    time.tm_sec = 0;
    t = mktime(&time);
    return (int)t;
}

string unix2time(int n,int format)
{
    char s[100] = {0};
    memset(s, 0, 100);
    time_t tick = (time_t)(n);
    struct tm *tm = localtime(&tick);
	switch (format)
	{
		case TIEM_TYPE_DATE:	//DATA:	20201030
		    strftime(s, sizeof(s), "%Y%m%d", tm);
			break;
		default: //TIME: 2020-10-30 10:10:10
			strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", tm);
			break;
	}
    return string(s);
}

int main()
{
    string ret;
    string str = "20200131";
    int a = 0;
    a = time2unix(str);
    cout << a << endl;
    if (a == 0)
        ret = unix2time(a);
    else
    {
        a += 86400;
        ret = unix2time(a);
    }
    cout << ret << endl;
}

有时候unix时间戳会以16进制形式存在,先将16进制转成10进制

int hex_to_dec(char* a)
{
	int len = strlen(a);
	int sum = 0;
	for (int i = 0; i < len; i++)
	{
		if (a[i] >= 'A' && a[i] <= 'F')
		{
			a[i] = int(a[i] - 'A') + 10 + '0';
		}

		if (a[i] >= 'a' && a[i] <= 'f')
		{
			a[i] = int(a[i] - 'a') + 10 + '0';
		}
		sum += (a[i] - '0') * (pow(16.0, len - 1 - i));
	}
	return sum;
}

参考博客:

UNIX时间戳和北京时间的相互转换

Unix时间戳和北京时间的相互转换(C语言实现 )

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值