使用 sscanf 将字符串转换为时间 [英] converting string into time using sscanf

查看:78
本文介绍了使用 sscanf 将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Windows 上将时间字符串转换为 C 中的时间格式.由于我的字符串中只有小时、分钟和秒,因此尝试使用 sscanf 将字符串解析为时间格式,然后使用 mktime.但不知何故它没有将其转换为时间格式.为了检查,我尝试将转换后的时间打印回字符串.代码如下:

I am trying to convert time string into time format in C on windows. As i just have hour, minutes and seconds in my string, so tried to parse the string using sscanf into time format and then use mktime. But somehow its not converting it into time format. To check, i tried to print the converted time into string back. The code looks like:

struct tm tm;
char time_buffer[100];
int hh, mm;
float ms;
time_t time_value;
char *timestamp = {"16:11:56.484"};
sscanf(timestamp, "%d:%d:%f", &hh, &mm,&ms);
tm.tm_hour =hh;
tm.tm_min = mm;
tm.tm_sec = ms*1000;
tm.tm_isdst = -1;
time_value = malloc(100*sizeof(char));
time_value = mktime(&tm);
if (time_value==-1)
    printf ("unable to make time");
strftime(time_buffer, sizeof(time_buffer), "%c", &tm);
printf(time_buffer);

推荐答案

在调用mktime()之前,代码需要初始化tm_struct()的7+个字段:<代码>年、月、日、小时、分钟、秒、isdst 和其他可能的.

Before calling mktime(), code needs to initialize 7+ fields of tm_struct(): year, month,day, hour min, sec, isdst and potentially others.

2 个例外:.tm_yday, .tm_wday 在调用 mktime() 之前不需要赋值.

2 exceptions: .tm_yday, .tm_wday do not need assignment before calling mktime().

年、月、日应该设置为合理的值:让我们使用 2000 Jan 1.或者代码可以使用 time_t() 来获取今天.

The year, month, day should be set to something reasonable: let us use 2000 Jan 1. Alternatively code could use time_t() to get today.

Code 使用 ms 暗示该值以毫秒为单位.它不是.还差几秒.

Code uses ms hinting that the value is in milliseconds. It is not. It is still in seconds.

使用本地 time_t 变量而不是分配一个.malloc() 不需要.

Use local time_t variable rather than allocating one. malloc() not needed.

struct tm tm = {0};
tm.tm_year = 2000 - 1900;  // Years from 1900
tm.tm_mon = 1 - 1; // Months from January
tm.tm_mday = 1;
char time_buffer[100];
int hh, mm;
float ss;
time_t time_value;
char *timestamp = "16:11:56.484";

if (sscanf(timestamp, "%d:%d:%f", &hh, &mm,&ss) != 3) Handle_BadData();
tm.tm_hour = hh;
tm.tm_min = mm;
tm.tm_sec = roundf(ss);  // or simply = ss;
tm.tm_isdst = 0;  // Keep in standard time
// time_value = malloc(100*sizeof(char));
time_value = mktime(&tm);
if (time_value == -1) {
    printf ("unable to make time");
}
else {
  strftime(time_buffer, sizeof(time_buffer), "%c", &tm);
  printf(time_buffer);
}

// Sat Jan  1 16:11:56 2000

这篇关于使用 sscanf 将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆