C++ Get Current Time 获取当前时间

在C++中获取系统当前时间通常涉及使用ctime库。本文介绍了如何使用ctime库的ctime()函数和tm结构体来获取并格式化日期和时间。还提到了C++11中的std::chrono库作为另一种时间操作的现代方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做项目中,我们经常需要获取系统的当前时间,那么如何获取呢,参见下面的代码:

/* asctime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, time, localtime, asctime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "The current date/time is: %s", asctime (timeinfo) );

  return 0;
}

输出结果为:

The current date/time is:: Thu Feb 26 11:40:19 2015

但是,有些情况下我们想分别获得年月日时分秒的值,而不是像这样得到一个整个的字符串,那么既然时间信息都存在了一个结构体timeinfo中,那么我们就先来看看这个结构体的定义吧:

struct tm {
  int tm_sec;   // seconds of minutes from 0 to 61
  int tm_min;   // minutes of hour from 0 to 59
  int tm_hour;  // hours of day from 0 to 24
  int tm_mday;  // day of month from 1 to 31
  int tm_mon;   // month of year from 0 to 11
  int tm_year;  // year since 1900
  int tm_wday;  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值