c++获得当前时间的有甚么方法
在C++中获得当前时间的方法有以下几种:
1. 使用time函数:time函数返回自1970年1月1日以来经过的秒数,可使用time(NULL)来获得当前时间的秒数。
```c++
#include
#include
int main() {
time_t now = time(NULL);
std::cout << "Current time: " << now << std::endl;
return 0;
}
```
2. 使用ctime函数:ctime函数将time_t类型的时间转换为字符串格式,可使用time(NULL)来获得当前时间的秒数,然后再将其转换为字符串。
```c++
#include
#include
int main() {
time_t now = time(NULL);
std::cout << "Current time: " << ctime(&now);
return 0;
}
```
3. 使用chrono库:C++11引入了chrono库,可以方便地操作时间和延续时间。可使用std::chrono::system_clock::now()来获得当前时间的时间点。
```c++
#include
#include
int main() {
auto now = std::chrono::system_clock::now();
std::time_t current_time = std::chrono::system_clock::to_time_t(now);
std::cout << "Current time: " << std::ctime(¤t_time);
return 0;
}
```
注意:以上方法中,使用ctime函数获得的时间字符串包括了换行符,可使用其他方法去除换行符。
TOP