C++ Date & Time
C ++标准库不提供正确的日期类型。 C ++从C继承了日期和时间操作的结构和函数。要访问与日期和时间相关的函数和结构,您需要在C ++程序中包含
头文件。
有四种与时间相关的类型:
clock_t, time_t, size_t
和
tm
。 类型 - clock_t,size_t和time_t能够将系统时间和日期表示为某种整数。
结构类型
tm
以具有以下元素的C结构的形式保存日期和时间 -
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; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
以下是我们在使用C或C ++处理日期和时间时使用的重要函数。 所有这些函数都是标准C和C ++库的一部分,您可以参考下面给出的C ++标准库来检查它们的详细信息。
|
Sr.No
|
功能与目的
|
|
1
|
time_t time(time_t *time);
这将返回自1970年1月1日以来经过的秒数内系统的当前日历时间。如果系统没有时间,则返回.1。
|
|
2
|
char *ctime(const time_t *time);
这将返回指向表格
day month year hours:minutes:seconds year\n\0
的字符串的指针
day month year hours:minutes:seconds year\n\0
。
|
|
3
|
struct tm *localtime(const time_t *time);
这将返回指向表示本地时间的
tm
结构的指针。
|
|
4
|
clock_t clock(void);
这将返回一个值,该值近似于调用程序运行的时间。 如果时间不可用,则返回值.1。
|
|
5
|
char * asctime ( const struct tm * time );
这将返回一个指向字符串的指针,该字符串包含存储在转换为表单的时间所指向的结构中的信息:day month date hours:minutes:seconds year\n\0
|
|
6
|
struct tm *gmtime(const time_t *time);
这将以tm结构的形式返回指向时间的指针。 时间以协调世界时(UTC)表示,其基本上是格林威治标准时间(GMT)。
|
|
7
|
time_t mktime(struct tm *time);
这将返回与time指向的结构中找到的时间等效的日历时间。
|
|
8
|
double difftime ( time_t time2, time_t time1 );
此函数计算time1和time2之间的秒数差异。
|
|
9
|
size_t strftime();
此功能可用于以特定格式格式化日期和时间。
|
当前日期和时间
假设您要检索当前系统日期和时间,可以是本地时间,也可以是协调世界时(UTC)。 以下是实现相同的例子 -
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
编译并执行上述代码时,会产生以下结果 -
The local date and time is: Sat Jan 8 20:07:41 2011
The UTC date and time is:Sun Jan 9 03:07:41 2011
使用struct tm格式化时间
在C或C ++中使用日期和时间时,
tm
结构非常重要。 该结构以如上所述的C结构的形式保持日期和时间。 大多数时候相关的函数都使用了tm结构。 以下是一个利用各种日期和时间相关函数和tm结构的例子 -
在本章中使用结构时,我假设您对C结构以及如何使用arrow - >运算符访问结构成员有基本的了解。
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970:" << now << endl;
tm *ltm = localtime(&now);
// print various components of tm structure.
cout << "Year" << 1970 + ltm->tm_year<<endl;
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< 1 + ltm->tm_hour << ":";
cout << 1 + ltm->tm_min << ":";
cout << 1 + ltm->tm_sec << endl;
编译并执行上述代码时,会产生以下结果 -
Number of sec since January 1, 1970:1294548238
Year: 2011
Month: 1
Day: 8
Time: 22: 44:59