21xrx.com
2025-04-27 08:31:20 Sunday
文章检索 我的文章 写文章
C++获取本地时间的方法简介
2023-06-23 16:47:28 深夜i     14     0
C++ 获取本地时间 方法简介

在C++开发中,获取本地时间是经常用到的操作,可能用于日志记录、定时任务等项目中。下面将介绍几种获取本地时间的方法。

一、使用ctime库函数

ctime库提供了localtime()函数,该函数将time_t类型的时间转换为tm结构体类型的本地时间,并返回指向该结构体类型的指针。

示例代码如下:

#include <ctime>
#include <iostream>
using namespace std;
int main()
{
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  cout << "The current date/time is: " << asctime(timeinfo);
  return 0;
}

运行结果如下:

The current date/time is: Mon Sep 20 17:31:09 2021

二、使用C++11标准库chrono

C++11标准库提供了chrono库,其中包含system_clock类,可以获取当前系统时间。先获取当前系统时间的time_point类型,再转换为tm结构体类型的本地时间。

示例代码如下:

#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
int main()
{
  auto now = chrono::system_clock::now();
  time_t t = chrono::system_clock::to_time_t(now);
  struct tm* local_t = localtime(&t);
  cout << "The current date/time is: " << asctime(local_t);
  return 0;
}

运行结果如下:

The current date/time is: Mon Sep 20 17:31:09 2021

三、使用Windows API函数

在Windows平台下,可以使用Windows API函数来获取本地时间。其中用到的主要函数是GetLocalTime()和GetSystemTime()。

示例代码如下:

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
  WCHAR dateStr[9], timeStr[9];
  SYSTEMTIME sysTime;
  GetLocalTime(&sysTime);
  GetDateFormat(LOCALE_USER_DEFAULT, 0, &sysTime, L"yyyyMMdd", dateStr, 9);
  GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, L"HH:mm:ss", timeStr, 9);
  wcout << dateStr << L" " << timeStr << endl;
  return 0;
}

运行结果如下:

20210920 17:31:09

以上就是几种获取本地时间的方法介绍。针对不同的需求,可以选择不同的方法来获取本地时间。

  
  

评论区