如何擷取系統目前時間

來源:互聯網
上載者:User

需要的標頭檔

#include<time.h>
先做一個擷取系統目前時間的範例,再來解釋所用的函數的作用
程式碼範例:
#include<stdio.h>

#include<time.h>

int main()
{
   time_t   timep;//定義 time_t類型變數timep,類型為long int型
  
   time( &timep );//把擷取的時間儲存
  
    //printf("%s", asctime ( localtime( &timep ) ) );
//把本地時間轉化為ASCII碼列印出來
 
  return 0;
}
函數定義
char *asctime(const struct tm *timeptr)
函數說明
asctime()將參數timeptr所指的tm結構中的資訊轉換成真實世界所使用的時間日期表示方法,
結果以字串形式返回 ,此函數已有時區轉換為當地時間 
 
  localtime()
    
 功 能: 把從1970-1-1零點零分到目前時間系統所位移的秒數時間轉換為本地時間,
而gmtimes函數轉換後的時間沒有經過時區變換,是UTC時間 。

說明:此函數獲得的tm結構體的時間是日曆時間。

用 法: struct tm *localtime(const time_t *clock);

傳回值:返回指向tm 結構體的指標.tm結構體是time.h中定義的用於分別儲存時間的各個量(年月日等)的結構體.
 
下面寫了一個詳細的用localtime()和asctime()的用法的程式碼範例


#include<stdio.h>

#include<time.h>

int main()
{
   time_t   timep;//定義 time_t類型變數timep ,類型為long int型
   struct tm *block;

   timep=time(NULL);//返回目前時間與1970年1月1日0時0分0秒相差的多少秒

   printf("%ld\n",timep);
  
   block=localtime(&timep );//把擷取的時間儲存

   printf("%s", asctime (  block) );//把本地時間轉化為ASCII碼列印出來

 return 0;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.