How can you convert date formats in the C programming l…
In C language, you can use the strftime function to convert date formats. The prototype of the strftime function is as follows:
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
Explanation of parameters:
- str: pointer to a string for storing the conversion result.
- maximum size: the maximum length of the string pointed to by str.
- String for changing format.
- timeptr: pointer to a tm structure, indicating the date and time to be converted.
Below is an example of converting the current date and time into a specified format string:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("Formatted date and time: %s\n", buffer);
return 0;
}
Output: result
Formatted date and time: 2022-01-01 12:34:56
Different format specifiers can be used in the third parameter of the strftime function to define various date and time formats. For example, %Y represents a four-digit year, %m represents a two-digit month, %d represents a two-digit day, %H represents hours in 24-hour format, %M represents minutes, %S represents seconds. More detailed format specifiers can be found in the relevant documentation for the C language.