Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ใช้ time.h แสดงวันที่และเวลาปัจจุบันในรูปแบบ ISO ใน C


โจทย์

แสดงวันที่และเวลาปัจจุบันในรูปแบบ ISO standard (เช่น Mon, 15 Dec 2020 10:50)

ฟังก์ชันหลัก

  • time() - คืนค่าเวลาปัจจุบัน (time_t)
  • strftime() - แปลงเวลาเป็นสตริงตามรูปแบบ (ใน time.h)
  • localtime() - แปลง time_t เป็น struct tm

โปรแกรมตัวอย่าง

#include <stdio.h>
#include <time.h>

int main() {
    time_t current = time(NULL);
    char datetime[50];
    
    strftime(datetime, sizeof(datetime), "%a, %d %b %Y %H:%M", localtime(¤t));
    puts(datetime);
    return 0;
}

ผลลัพธ์

Thu, 31 Dec 2020 22:41

รูปแบบ Format String ที่ใช้บ่อย

  • %a - วันสั้น (Thu)
  • %d - วันที่ (01-31)
  • %b - เดือนสั้น (Dec)
  • %Y - ปี 4 หลัก (2020)
  • %H:%M - ชั่วโมง:นาที (24 ชม.)