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

ฟังก์ชัน strftime() ใน C/C++: จัดรูปแบบวันที่และเวลา

ฟังก์ชัน strftime() ใช้จัดรูปแบบวันที่และเวลาเป็น String ตาม Locale ที่กำหนด อยู่ใน Header <time.h>

ไวยากรณ์

#include <time.h>
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
  • str - Buffer รับผลลัพธ์
  • maxsize - ขนาด Buffer สูงสุด (ป้องกัน Overflow)
  • format - Format String มี Specifiers ต่างๆ
  • timeptr - Pointer to struct tm (Broken-down Time)
  • คืนค่า: จำนวนตัวอักษรที่เขียน (ไม่รวม Null Terminator) หรือ 0 ถ้า Buffer เล็กเกินไป

ตัวอย่าง

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

int main() {
    time_t rawtime;
    struct tm *timeinfo;
    char buffer[80];
    
    time(&rawtime);                    // เวลาปัจจุบัน (Unix Timestamp)
    timeinfo = localtime(&rawtime);    // แปลงเป็น Local Time (struct tm)
    
    // จัดรูปแบบ: MM/DD/YY - HH:MM AM/PM
    strftime(buffer, sizeof(buffer), "%x - %I:%M%p", timeinfo);
    
    printf("Formatted Date & Time: %s\n", buffer);
    return 0;
}

ผลลัพธ์ตัวอย่าง

Formatted Date & Time: 10/23/18 - 10:33AM

Format Specifiers สำคัญ

ตัวอย่าง Format Patterns

strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);  // 2024-12-25 14:30:45
strftime(buf, sizeof(buf), "%A, %B %d, %Y", tm);      // Wednesday, December 25, 2024
strftime(buf, sizeof(buf), "%I:%M %p", tm);           // 02:30 PM
strftime(buf, sizeof(buf), "Week %U of %Y", tm);      // Week 52 of 2024

struct tm Fields

struct tm {
    int tm_sec;    // Seconds [0, 60]
    int tm_min;    // Minutes [0, 59]
    int tm_hour;   // Hours [0, 23]
    int tm_mday;   // Day of Month [1, 31]
    int tm_mon;    // Month [0, 11] (Jan = 0!)
    int tm_year;   // Years since 1900
    int tm_wday;   // Day of Week [0, 6] (Sun = 0)
    int tm_yday;   // Day of Year [0, 365]
    int tm_isdst;  // Daylight Saving Time Flag
};

ฟังก์ชันเกี่ยวข้อง

  • time() - ได้ Unix Timestamp (time_t)
  • localtime() - แปลง time_t → struct tm (Local Time, Not Thread-safe)
  • gmtime() - แปลง time_t → struct tm (UTC, Not Thread-safe)
  • localtime_r(), gmtime_r() - Thread-safe Versions (POSIX)
  • mktime() - แปลง struct tm → time_t (Normalize Fields)

C++ Alternative: และ (C++20)

#include <chrono>
#include <format>
#include <iostream>

int main() {
    auto now = std::chrono::system_clock::now();
    std::cout << std::format("{:%Y-%m-%d %H:%M:%S}", now) << '\n';
    return 0;
}
Specifierคำอธิบายตัวอย่าง
%Yปี 4 หลัก2024
%yปี 2 หลัก24
%mเดือน (01-12)12
%dวัน (01-31)25
%Hชั่วโมง 24H (00-23)14
%Iชั่วโมง 12H (01-12)02
%Mนาที (00-59)30
%Sวินาที (00-59)45
%pAM/PMPM
%aวันสั้น (Mon, Tue)Wed
%Aวันเต็ม (Monday)Wednesday
%bเดือนสั้น (Jan, Feb)Dec
%Bเดือนเต็ม (January)December
%cDate & Time ตาม LocaleWed Dec 25 14:30:45 2024
%xDate ตาม Locale12/25/24
%XTime ตาม Locale14:30:45
%%ตัว % ตรงๆ%