ฟังก์ชัน 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 tostruct 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 สำคัญ
| 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 |
%p | AM/PM | PM |
%a | วันสั้น (Mon, Tue) | Wed |
%A | วันเต็ม (Monday) | Wednesday |
%b | เดือนสั้น (Jan, Feb) | Dec |
%B | เดือนเต็ม (January) | December |
%c | Date & Time ตาม Locale | Wed Dec 25 14:30:45 2024 |
%x | Date ตาม Locale | 12/25/24 |
%X | Time ตาม Locale | 14:30:45 |
%% | ตัว % ตรงๆ | % |