代码
string currentDateToString()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
std::string str(buffer);
return str;
}
解析
time.h 包含时间相关的操作。
我们需主要如下内容:
- clock_t
用于存储处理机时间。
- time_t
用于存储日历时间。
- struct tm
用于表示时间类型 包含 时间和日期。详细如下:
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
需要留意的一些方法:
- char *asctime(const struct tm *timeptr)
将输入的结构类型timeptr 转换为字符串。
直接执行该方法可能会报错:
Severity Code Description Project File Line Suppression State
Error C4996 ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. GetCodec c:\code\gitproject\kiosk.k5project\opencvstudyhomenotebook\getcodec\getcodec.cpp 20
需要添加:
#pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS
屏蔽掉该警告
代码如下:
#pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<Windows.h>
#include<time.h>
#include<string>
int main()
{
/* std::cout << "Hello World!\n";
system("WPFDocumentPrint.exe");
system("pause");*/
//ShellExecuteA(NULL, "open", "WPFDocumentPrint.exe", NULL, NULL, SW_MAXIMIZE);
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
std::cout << std::string(asctime(timeinfo));
std::cout << "hello";
int a;
std::cin >> a;
return 0;
}
-
clock_t clock(void)
返回从程序开始执行时的处理器时间。 -
char *ctime(const time_t *timer)
Returns a string representing the localtime based on the argument timer. -
double difftime(time_t time1, time_t time2)
Returns the difference of seconds between time1 and time2 (time1-time2). -
struct tm *gmtime(const time_t *timer)
The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT). -
struct tm *localtime(const time_t *timer)
The value of timer is broken up into the structure tm and expressed in the local time zone. -
time_t mktime(struct tm *timeptr)
Converts the structure pointed to by timeptr into a time_t value according to the local time zone. -
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str. -
time_t time(time_t *timer)
Calculates the current calender time and encodes it into time_t format.