是否有一种跨平台的方法来在C++中获取当前日期和时间?
std::chrono::system_clock::now()
。#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s"
<< std::endl;
}
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
string
,或如何正确格式化time_point<>
感到困惑,请继续提出另一个问题或在谷歌上搜索它。 - TarcC++与C共享其日期/时间函数。对于C++程序员来说,tm结构可能是最容易使用的 - 以下代码打印出今天的日期:
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
ctime()
和这个答案。 - ralphtheninjastruct tm
实例,直接调用 delete
可行吗? - Petrdelete
(C++关键字)删除它,我只是认为它应该以某种方式被删除 :) 或者谁将为您执行此操作? - Petr#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
getchar(); // wait for keyboard input
}
输出:
currentDateTime()=2012-05-06.21:47:59
请访问此处了解有关日期/时间格式的更多信息。
localtime
已经被弃用,取而代之的是localtime_s
,其语法在不同的C实现中有所不同。微软的版本如下:errno_t err = localtime_s(&tstruct, &now);
- Antony Hatchkins一个老问题的新回答:
这个问题没有指定时区。有两种合理的可能性:
对于第一种情况,您可以使用这个日期库和下面的程序:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << system_clock::now() << '\n';
}
它只是为我输出了:
2015-08-18 22:08:18.944211
日期库本质上只是为 std::chrono::system_clock::time_point
添加了一个流操作符。它还添加了许多其他很好的功能,但在这个简单的程序中没有使用。
如果您喜欢2(本地时间),那么有一个基于 日期库 构建的 时区库。这两个库都是开源的 和 跨平台的,假设编译器支持C++11或C++14。
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto local = make_zoned(current_zone(), system_clock::now());
std::cout << local << '\n';
}
对我来说只是输出:
2015-08-18 18:08:18.944211 EDT
make_zoned( date::current_zone(), std::chrono::system_clock::now())
的结果类型是date::zoned_time
,它是一个date::time_zone
和一个std::chrono::system_clock::time_point
的配对。这个配对表示本地时间,但根据您查询它的方式,也可以表示UTC。
根据上面的输出,您可以看到我的电脑当前位于一个UTC偏移量为-4小时,缩写为EDT的时区。
如果需要使用其他时区,也可以实现。例如,要查找澳大利亚悉尼的当前时间,只需更改变量local
的构造方式:
auto local = make_zoned("Australia/Sydney", system_clock::now());
输出结果变为:
2015-08-19 08:08:18.944211 AEST
此库现在已经广泛应用于C++20。命名空间date
已经消失,现在所有内容都在命名空间std::chrono
中。使用zoned_time
代替make_time
。删除头文件"date.h"
和"tz.h"
,只需使用<chrono>
。
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto local = zoned_time{current_zone(), system_clock::now()};
std::cout << local << '\n'; // 2021-05-03 15:02:44.130182 EDT
}
当我写下这段话时,一些平台上的部分实现才刚刚开始出现。
localtime
不应该给我返回我的时区时间吗? - Jonathan Meelocaltime
函数几乎总是以秒为精度提供本地时区的时间。但有时由于线程安全问题会失败,并且它永远无法提供亚秒级别的精度。 - Howard Hinnantstd::cout << std::chrono::system_clock::now();
会失败。 - 463035818_is_not_a_numberC++标准库没有提供适当的日期类型。C++从C继承了日期和时间操作的结构体和函数,以及一些考虑本地化的日期/时间输入输出函数。
// Current date/time based on current system
time_t now = time(0);
// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.
使用std::time()
或std::chrono::system_clock::now()
(或其他clock type)获取当前时间。
std::put_time()
(C++11)和strftime()
(C)提供了许多格式化程序来输出这些时间。
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout
// ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
<< std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
// %m/%d/%y, e.g. 07/31/17
<< std::put_time(std::gmtime(&time), "%D");
}
std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday
strftime()
的格式化方式类似于:
char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}
本地设置会改变输出结果:
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_GB.utf8"));
std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("de_DE.utf8"));
std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ru_RU.utf8"));
std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");
}
undef: Tue Aug 1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30
std::gmtime()
将时间转换为UTC。std::localtime()
可用于将时间转换为本地时间。asctime()
/ctime()
现在已被标记为过时,应优先使用strftime()
。std::put_time()
无法使用 std::chrono::system_clock::now()
的输出。 - remcycles还有一个名为Boost::date_time的库:
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
是的,您可以使用当前加注区域指定的格式规则来进行此操作:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
timefmt(std::string fmt)
: format(fmt) { }
friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
std::ostream::sentry s(os);
if (s)
{
std::time_t t = std::time(0);
std::tm const* tm = std::localtime(&t);
std::ostreambuf_iterator<char> out(os);
std::use_facet<std::time_put<char>>(os.getloc())
.put(out, os, os.fill(),
tm, &mt.format[0], &mt.format[0] + mt.format.size());
}
os.width(0);
return os;
}
int main()
{
std::cout << timefmt("%c");
}
2013年9月6日星期五 20:33:31
ostream::sentry
). - DevSolar
tm
结构更好。C++11 方法只返回自 Unix 纪元以来的时间戳,而问题是如何获取日期和时间。 - Snackoverflow