首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言實例練習

C語言練習實例91:獲取並顯示當前本地時間

     編輯:C 語言實例練習

C語言練習實例91:獲取並顯示當前本地時間

本實例演示如何使用 time()、localtime() 和 asctime() 獲取並格式化輸出當前本地日期時間。

程序分析

  • time(&rawtime) 獲取當前時間戳(自 1970-01-01 以來的秒數)。
  • localtime() 將時間戳轉換為本地時間的 struct tm 結構。
  • asctime() 將 struct tm 格式化為可讀字符串(如 "Tue Nov 10 16:28:49 2015")。

源代碼

// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
#include <time.h>

int main() {
    time_t rawtime;
    struct tm *timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    printf("當前本地時間為: %s", asctime(timeinfo));

    return 0;
}

運行結果

當前本地時間為: Tue Nov 10 16:28:49 2015

擴展

  • 若需自定義格式,可使用 strftime() 函數。
  • gmtime() 可獲取 UTC 時間。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved