C++获取当前时间戳,并转化成格式化时间

#include<stdio.h>
#include<windows.h>
#include<iostream>
#include<time.h>
#include<sstream>
#include<chrono>
#include<string.h>
using namespace std;

typedef struct times
{
	int Year;
	int Mon;
	int Day;
	int Hour;
	int Min;
	int Second;
}Times;

Times stamp_to_standard(unsigned long long stampTime)
{
	time_t tick = (time_t)stampTime;
	struct tm tm;
	char s[100] = {0};
	Times standard;

	tm = *localtime(&tick);
	strftime(s, sizeof(s), "%Y/%m/%d %H:%M:%S", &tm);
	printf("%d: %s\n", (int)tick, s);


	standard.Year = atoi(s);
	standard.Mon = atoi(s + 5);
	standard.Day = atoi(s + 8);
	standard.Hour = atoi(s + 11);
	standard.Min = atoi(s + 14);
	standard.Second = atoi(s + 17);

	return standard;
}

void GetTimeFormStr(string TimeStr, Times &Mystandard)
{
	if (TimeStr.length() < 10)
	{
		return;
	}
	string pstr = TimeStr.substr(0, 10);
	stringstream s;
	s << pstr;
	unsigned long long i;
	s >> i;
	Mystandard = stamp_to_standard(i);
}

unsigned long long WINAPI GetTimeTickFrom19700101()
{
	SYSTEMTIME  systime;		//时间结构声明,这个结构是系统的,
	::GetLocalTime(&systime);
	time_t curr_t = time(NULL);
	unsigned long long tld = (unsigned long long)curr_t;
	unsigned long millSec = (unsigned long)(systime.wMilliseconds);
	tld = tld * 1000 + millSec;

	return tld;
}

void GetMytime(Times& standard)
{
	//
	//1.获取当前毫秒
	unsigned  long long  stampTime=GetTimeTickFrom19700101();

	//
	//2.longlong整型转string(这里是为了方便时间戳写入log文件或者注册表项中做记录)

	//方式一
	string Result;
	ostringstream convert;
	convert << stampTime;
	Result = convert.str();

	//方式二
	/*char str[30] = { 0 };
	sprintf(str, "%lld", stampTime);
	string Result(str);*/

	
	//3.从string中读取时间到结构体中
	GetTimeFormStr(Result, standard);
	
}

//从时间戳获取当前时间模块
int main()
{
	
	unsigned  long ticks;
	Times standard;
	for (int i = 0; i < 5; i++) {

	memset(&standard, 0, sizeof(Times));

	GetMytime(standard);

	char chrTime[100] = { 0 };
	sprintf(chrTime, "%04d%s%02d%s%02d%s%02d%s%02d%s%02d%s",
	standard.Year,
	"/",
	standard.Mon,
	"/",
	standard.Day,
	" ",
	standard.Hour,
	":",
	standard.Min,
	":",
	standard.Second,
	"[客户端]");

	cout << chrTime << endl;
	Sleep(1000);
	}
	system("pause");
	return 0;
}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值