我需要验证“YYYYMMDDHHMMSSmmmmmm
”格式的日期时间值。实际上我希望的是我需要找到一个已经测试过的工作 C 代码来验证上述格式的日期时间值。
此外,我有一个日期时间值,例如 201304011031000000
。我需要一个函数来验证这是否是有效日期。[isdatetime()
]
以下是格式的各个部分。
YYYY : Year
MM : Month
DD : Day
HH : hour
MM : Minutes
SS : seconds
mmmmmm: micro-seconds
最佳答案
如果您使用的是 POSIX 系统,这看起来应该用 strptime()
来处理。 ,但“毫秒”(或微秒)部分不是由 strptime()
或我知道的任何其他标准转换函数处理的。
假设问题要求微秒,您可以使用以下主题提供的变体:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void)
{
const char datetime[] = "20130417221633012345"; // YYYYMMDDHHMMSSFFFFFF
struct tm time_val;
unsigned microsecs;
const char *end = strptime(datetime, "%Y%m%d%H%M%S", &time_val);
if (end != 0)
{
int nbytes;
if (strlen(end) == 6 && sscanf(end, "%6u%n", µsecs, &nbytes) == 1 &&
nbytes == 6)
{
char buffer[32];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &time_val);
printf("%s = %s.%.6u\n", datetime, buffer, microsecs);
}
}
return 0;
}
<小时/>
修改后的要求
#include <stdio.h>
#include <string.h>
#include <time.h>
int isdatetime(const char *datetime)
{
// datetime format is YYYYMMDDHHMMSSFFFFFF
struct tm time_val;
unsigned microsecs;
int nbytes;
const char *end = strptime(datetime, "%Y%m%d%H%M%S", &time_val);
if (end != 0 && strlen(end) == 6 &&
sscanf(end, "%6u%n", µsecs, &nbytes) == 1 && nbytes == 6)
return 1; // Valid
return 0; // Invalid
}
关于用于日期时间格式验证的 C 代码。指定格式为 "YYYYMMDDHHMMSSmmmmmm",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16073876/