如何在C ++中获取当前时间和日期?

634

是否有一种跨平台的方法来在C++中获取当前日期和时间?


3
如果Ockonal仍在活跃,他应该将接受的答案更改为C++11方法。这个问题似乎仍然有很多人查看。 - JSQuareD
2
C语言版本:https://dev59.com/EHM_5IYBdhLWcg3wSBEU - Ciro Santilli OurBigBook.com
3
即使经过这么长时间后再看这个问题,我仍然认为使用 C 中的 tm 结构更好。C++11 方法只返回自 Unix 纪元以来的时间戳,而问题是如何获取日期和时间。 - Snackoverflow
5
哇,这个问题已经有 1,110,886 次浏览了!人们真的很喜欢 C++! - User123
4
不,他们只是讨厌::std::chrono。它是难以理解的胡言乱语。 - Yttrill
26个回答

2

1
时间_t rawTime; 时间(&rawTime); 结构tm *timeInfo; 字符串buf[80]; timeInfo = localtime(&rawTime); strftime(buf, 80, "%T", timeInfo);这个特定的代码只会输出HH:MM:SS。这是我的第一篇帖子,我不确定如何正确获取代码格式。对此感到抱歉。 - bduhbya

2

ffead-cpp提供了多个实用类以完成各种任务,其中一个是Date类,它从日期操作到日期算术运算都提供了很多功能,还有一个Timer类可用于计时操作。您可以查看这些类。


1
你可以使用boost和chrono库:
#include <iostream>
#include <chrono>
#include <boost/date_time/posix_time/posix_time.hpp>

using boost::posix_time::to_iso_extended_string;
using boost::posix_time::from_time_t;
using std::chrono::system_clock;

int main()
{
  auto now = system_clock::now();
  std::cout << to_iso_extended_string(from_time_t(system_clock::to_time_t(now)));
}

1
#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17 
// IDE: Visual Studio
int main() {
    using namespace std; 
    using namespace chrono;
    time_point tp = system_clock::now();
    time_t tt = system_clock::to_time_t(tp);
    cout << "Current time: " << ctime(&tt) << endl;
    return 0;
}

0
#include <Windows.h>

void main()
{
     //Following is a structure to store date / time

SYSTEMTIME SystemTime, LocalTime;

    //To get the local time

int loctime = GetLocalTime(&LocalTime);

    //To get the system time

int systime = GetSystemTime(&SystemTime)

}

7
问题要求跨平台。Windows.h 是针对 Windows 的,而 void main 甚至不是标准的 C/C++。 - derpface

-3

我需要一种在列表更新时插入当前日期时间的方法。 这种简单明了的方法似乎很有效。

#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int main()
{   //initialize variables
    time_t now; 
    //blah..blah
    /*each time I want the updated stamp*/
    now=time(0);cout<<ctime(&now)<<"blah_blah";
}

这个问题已经有很多答案了,包括展示如何使用 time() 的答案,所以这个答案并没有添加任何新内容。 - Jan
@Jan,那个#include <bits/stdc++.h>是一个非常不好的做法。 - SimonC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接