🕐⚡Beginner
Format Time in AM-PM Format
AM/PM time formatting
Format time in 12-hour AM/PM format.
Program Code
time_am_pm.c
C
1#include <stdio.h>2#include <time.h>34int main() {5 time_t now;6 struct tm *local;7 8 time(&now);9 local = localtime(&now);10 11 int hour = local->tm_hour;12 int min = local->tm_min;13 int sec = local->tm_sec;14 15 char *period = (hour >= 12) ? "PM" : "AM";16 int hour12 = hour % 12;17 if (hour12 == 0) hour12 = 12;18 19 printf("24-hour format: %02d:%02d:%02d\n", hour, min, sec);20 printf("12-hour format: %02d:%02d:%02d %s\n", hour12, min, sec, period);21 22 // Using strftime23 char buffer[50];24 strftime(buffer, sizeof(buffer), "%I:%M:%S %p", local);25 printf("Using strftime: %s\n", buffer);26 27 return 0;28}Output
24-hour format: 14:30:45
12-hour format: 02:30:45 PM
Using strftime: 02:30:45 PM
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials