Some functions about time

    時間的儲存,通過預定義的兩種結構來存儲:
1.日曆時間(Calendar Time)是通過time_t數據類型來表示的,用time_t表示的時間(日曆時間)是從一個時間點(例如:1970年1月1日0時0分0秒)到此時的秒數。在time.h中,我們也可以看到time_t是一個長整型數:
#ifndef _TIME_T_DEFINED
typedef long time_t;        
#define _TIME_T_DEFINED     
#endif

2.在標準C/C++中,我們可通過tm結構來獲得日期和時間,tm結構在time.h中的定義如下:
struct tm {
        int tm_sec;    
        int tm_min;    
        int tm_hour;   
        int tm_mday;   
        int tm_mon;    
        int tm_year;   
        int tm_wday;   
        int tm_yday;   
        int tm_isdst;  
        };

 

方法1.

/*獲取當前時間 按字符串格式輸出*/

#include <stdio.h>
#include <time.h>
void main()
{
 time_t timep;
 time (&timep);                /*獲取時間*/
 printf("%s",ctime(&timep)); 
}

 

方法2.

/*獲取當前時間,時、分、秒按自己需要顯示*/
#include <stdio.h>
#include <time.h>
void main()
{
 time_t timep;
 struct tm *p;
 time(&timep);
 p=localtime(&timep); /*取得當地時間*/
 printf("%d-%d-%d", (1900+p->tm_year),(1+p->tm_mon), p->tm_mday);
 printf("  %d:%d:%d/n",p->tm_hour, p->tm_min, p->tm_sec);
}

 

方法3.

#include <stdio.h>
#include <windows.h>

void main()
{
SYSTEMTIME  time;
char            buf[256];

GetLocalTime(&time);     //windows API函數
sprintf(buf, "%04d%02d%02d%02d%02d%02d", time.wYear, time.wMonth, time.wDay, time.wHour,    time.wMinute, time.wSecond);
 printf("%s/n", buf);
}

 

方法4.

#include <time.h>
#include <stdio.h>
int main( void )
{
 time_t      t; 
 char tmp[64];

 

 t = time(0);     //得到當前時間的值
 strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t) );     //格式化一個時間字符串
 puts( tmp );
 return 0;
}

 

方法5.       //C++
#include<iostream>
using namespace std;
void main()
{
  system("time");              //可以修改系統的時間
}

 

方法6.      //C++

#include<iostream>
#include<ctime>
using namespace std;

void main()
{
  time_t          now_time;
  now_time = time(NULL);
  cout<<now_time;
}

 

發佈了22 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章