在Cfree里编程,往往遇到很多代码一行不能写完的,所以遇到这种情况就是要加换行符\,以延续你想输出的语句。如果想直接换行,就用endl即可。
如下代码:
#include <time.h>
#include <iostream>
using namespace std;
int main(void)
{
struct tm *local; //tm为日期和时间的结构体,time头文件就包含了
time_t lt; //定义时间的对象
lt = time(NULL); //NULL为指针初始化
local = localtime(<);
cout << "Local time is:" << dec << local->tm_year <<" year" \
<< dec << local->tm_mon << " month" << \
dec << local->tm_mday << " day" << endl;
cout << dec << local->tm_hour << " hour" << \
dec << local->tm_min << " minute" << \
dec << local->tm_sec << " second" << endl;
local = gmtime( <);
cout << "UTC hour is:" << dec << local->tm_hour << endl;
return 0;
}
以上是调用了tm结构体,用localtime显示当前的时间,gmtime就是显示的UTC时间,UTC的全称是Universal Time Coodinated,又为世界标准时间。
调试了上面的代码,发现直接用localtime调用显示的年月日不准确,确定采用以下实现:
struct tm* ptr;
time_t lt;
lt = time(NULL);
ptr = gmtime(<);
cout << asctime(ptr) << endl;
cout << ctime(<) << endl;
return 0;
结果输出正确,asctime调用的是UTC时间,而ctime即为北京时间,百试不爽呢,各位请试一下吧。
其实,关于调用时间的函数还有很多,具体请参考博客点击打开链接
到底localtime和ctime有何区别呢?原来是C标准的原因,年要加1900,因为是从1900年开始保存的数据库,而月要加1,如下local->tm_year+1900;local->tm_mon+1。这样输出的时间就对了。
#include <time.h>
#include <iostream>
using namespace std;
int main(void)
{
struct tm *local;
time_t lt;
lt = time(NULL);
local = localtime(<);
cout << "Local time is:" << dec << local->tm_year+1900 <<" year"<<" " \
<< dec << local->tm_mon+1 << " month" <<" "<< \
dec << local->tm_mday << " day" << " "<< endl;
cout << dec << local->tm_hour << " hour" << " "<< \
dec << local->tm_min << " minute"<< " " <<\
dec << local->tm_sec << " second" << " "<< endl;
local = gmtime( <);
cout << "UTC hour is:" << dec << local->tm_hour << endl;
return 0;
}
输出为: