#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;
}
运行结果: