c語言的時間

c 語言獲得時間有兩種:

struct tm * gmtime(const time_t *timer); //將日曆時間轉化爲世界標準時間(即格林尼治時間)

int main()
{
    time_t timep;
    struct tm *p;
    time (&timep);
    p=gmtime(&timep);
    printf("%d\n",p->tm_sec); /*獲取當前秒*/
    printf("%d\n",p->tm_min); /*獲取當前分*/
    printf("%d\n",8+p->tm_hour);/*獲取當前時,這裏獲取西方的時間,剛好相差八個小時*/
    printf("%d\n",p->tm_mday);/*獲取當前月份日數,範圍是1-31*/
    printf("%d\n",1+p->tm_mon);/*獲取當前月份,範圍是0-11,所以要加1*/
    printf("%d\n",1900+p->tm_year);/*獲取當前年份,從1900開始,所以要加1900*/
    printf("%d\n",p->tm_yday); /*從今年1月1日算起至今的天數,範圍爲0-365*/
}

struct tm * localtime(const time_t * timer); //將日曆時間轉爲本地時間將通過time()函數返回的值,轉成時間結構structtm :

形式爲struct tm *localtime (const time_t *__timer);
其中tm爲一個結構體,包含了年月日時分秒等信息。
這種結構是適合用來輸出的。

#include <stdio.h>
#include <time.h>
int main ()
{
    time_t t;
    struct tm * lt;
    time (&t);//獲取Unix時間戳。
    lt = localtime (&t);//轉爲時間結構。
    printf ( "%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);//輸出結果
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章