C++時間標準庫時間time和系統時間的使用
1. C++標準庫中的時間需要引用time.h,可以取的本地時間或者格林威治時間,只能精確到秒 #include <iostream>
/*包含time頭文件*/
#include <time.h>
using namespace std;
int main()
{
//time_t是long類型,精確到秒,是當前時間和1970年1月1日零點時間的差
const time_t t = time(NULL);
cout<<"current time is "<<t<<endl;
/*本地時間:日期,時間 年月日,星期,時分秒*/
struct tm* current_time = localtime(&t);
printf("current year is %d;current month is %d;current date of month is %d\r\n",
1900 + current_time->tm_year,
1 + current_time->tm_mon/*此month的范圍為0-11*/,
current_time->tm_mday);
printf("current day of year is %d;current day in week is %d\r\n",
current_time->tm_yday,/*當前日期是今年的第多少天[0,365] */
current_time->tm_wday/*days since Sunday - [0,6] */);
printf("time part %d:%d:%d \r\n",
current_time->tm_hour,
current_time->tm_min,
current_time->tm_sec);
printf("\t本地時間:%d-%d-%d %d:%d:%d\r\n",
current_time->tm_year + 1900,
current_time->tm_mon + 1,
current_time->tm_mday,
current_time->tm_hour,
current_time->tm_min,
current_time->tm_sec);
/*格林威治時間*/
struct tm* current_gmtime = gmtime(&t);
printf("格林威治時間:%d-%d-%d %d:%d:%d\r\n",
current_gmtime->tm_year + 1900,
current_gmtime->tm_mon + 1,
current_gmtime->tm_mday,
current_gmtime->tm_hour,
current_gmtime->tm_min,
current_gmtime->tm_sec);
system("pause");
return 0;
}
2. 系統時間 SYSTEMTIME 使用時要引用windows.h,可以精確到毫秒級別 #include <iostream>
#include <Windows.h>
int main(){
//聲明變量
SYSTEMTIME sys_time;
//將變量值設置為本地時間
GetLocalTime( &sys_time );
//輸出時間
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n",sys_time.wYear,
sys_time.wMonth,
sys_time.wDay,
sys_time.wHour,
sys_time.wMinute,
sys_time.wSecond,
sys_time.wMilliseconds,
sys_time.wDayOfWeek);
system("time");
system("pause");
return 0;
}
#include <iostream> #include <Windows.h> int main(){ //聲明變量 SYSTEMTIME sys_time; //將變量值設置為本地時間 GetLocalTime( &sys_time ); //輸出時間 printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n",sys_time.wYear, sys_time.wMonth, sys_time.wDay, sys_time.wHour, sys_time.wMinute, sys_time.wSecond, sys_time.wMilliseconds, sys_time.wDayOfWeek); system("time"); system("pause"); return 0; }
本文由用戶 xdfr 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!