C Program : Basic technique for changing time format

in c-programming •  2 years ago 

Welcome back,
Yesterday we learnt how to show current date and time using C programming language. There was a question i asked yesterday, in yesterday's program output the time was shown in 24 hours time format.

How to change this to Am/Pm format was what i asked yesterday. Let us look at how to convert 24 hours time format to AM/PM time format.

Here is the code itself.

Screenshot 2023-02-19 203658.png

Copy the code from below :

#include <stdio.h>

int main()
{
int hour, minute;
char meridian[3];

printf("Enter the time in 24-hour format (HH:MM): ");
scanf("%d:%d", &hour, &minute); // get input from user

// Determine the meridian (AM or PM)
if (hour < 12) {
sprintf(meridian, "AM");
if (hour == 0) {
hour = 12;
}
} else {
sprintf(meridian, "PM");
if (hour > 12) {
hour = hour - 12;
}
}

printf("The time in AM/PM format is: %02d:%02d %s", hour, minute, meridian);

return 0;
}

In this program, we first get the time input from the user in 24-hour format using the scanf function. We then determine whether the time is in the AM or PM by checking whether the hour is less than 12. If it is, the meridian is "AM". If not, the meridian is "PM" and we subtract 12 from the hour to convert it to 12-hour format.

Finally, we print out the converted time in the format "HH:MM AM/PM" using the printf function.

Below are the time output for the program we wrote above.

Screenshot 2023-02-19 203712.png

Screenshot 2023-02-19 203720.png

Now i have not taken the yesterday's program and only shown how you can change HH to AM/PM. I did this because now you can try implementing it in yesterday's program.

If you also want to learn basics and start your C programming journey then find a teacher today for free on Youtube.

I learnt alot from a teacher who teaches c in hindi and if you are finding someone who teaches in hindi then this person will definitely help you.

Source

I am happy to call myself a trader and small programmer at the same time now.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  

Keep it Up..Pros also began like this

  ·  2 years ago  ·  

Bro you are doing amazing work


Posted from https://blurtlatam.intinte.org