strptime函数将字符串转换为时间格式代码
时间: 2023-06-05 21:05:56 浏览: 112
把字符串转化为时间格式
5星 · 资源好评率100%
Sure, the strptime function in C is used to convert a string to a time format. The syntax for the function is:
```
#include <time.h>
char *strptime(const char *s, const char *format, struct tm *tm);
```
Here, `s` is the string you want to convert, `format` is the format of that string, and `tm` is the structure that will hold the converted time. The function returns a pointer to the end of the converted string, or NULL if the conversion failed.
An example usage of this function would be:
```
#include <stdio.h>
#include <time.h>
int main()
{
char dateString[] = "2022-01-01 12:00:00";
char formatString[] = "%Y-%m-%d %H:%M:%S";
struct tm timeStruct;
strptime(dateString, formatString, &timeStruct);
printf("Year: %d\n", timeStruct.tm_year + 1900); // tm_year starts from 1900
printf("Month: %d\n", timeStruct.tm_mon + 1); // tm_mon starts from 0
printf("Day: %d\n", timeStruct.tm_mday);
printf("Hour: %d\n", timeStruct.tm_hour);
printf("Minute: %d\n", timeStruct.tm_min);
printf("Second: %d\n", timeStruct.tm_sec);
return 0;
}
```
阅读全文