【问题标题】:I am trying to calculate an age based on birthdate given and the current date in c我正在尝试根据给定的出生日期和 c 中的当前日期来计算年龄
【发布时间】:2014-02-04 22:43:08
【问题描述】:

我正在为我的 unix 课程用 c 创建一个程序。我正在尝试创建一个函数来查找当前日期,获取个人出生日期(存储在 **individual 字符串中),并使用它们来计算个人年龄(以年和月为单位)。我不确定如何解决这个问题,因为当前日期存储在 struct tm 中,而个人生日存储在字符串中。 (对c很陌生,才学了几天)。下面是我这个函数的代码,如果有人可以请给我一些建议,谢谢。

char* calcage(char **individual, char **age)
{
    time_t time_raw_format;
    struct tm * time_struct;
    char *lastname = (char *)malloc(50*sizeof(char));
    char *lnamefile = (char *)malloc(50*sizeof(char));
    char buf [100];

    time ( &time_raw_format );
    time_struct = localtime ( &time_raw_format );

    strftime (buf,100,"It is: %m/%d/%Y.",time_struct);
    puts (buf);

    printf("person: %s\n", *individual);

    lastname = strrchr(*individual, ',');
    lastname++;
    //lnamefile = strtok(lastname, searchseperator);
    printf("Individual:  %s\n", lastname);

  }

【问题讨论】:

  • 将字符串中的日期转换为时间,然后做任何你需要做的计算。
  • 建议struct tm time_struct; time_struct = *localtime ( &time_raw_format );

标签: c date


【解决方案1】:

这里的典型方法是将两个日期都转换为规范的时间戳格式。 解析字符串见:http://www.gnu.org/software/libc/manual/html_node/Parsing-Date-and-Time.html

一旦您拥有 UNIX 时间戳格式的两种格式,您就可以减去然后再转换回年份。不过也有一些注意事项:

  • 如果由于闰年而仅假设每年 365 天,则转换回年份是不准确的。这是一种非常微妙的影响,在极少数情况下会导致计算错误(通常称为“在客户处”)。
  • UNIX 时间戳始于 1970 年,人们出生在此之前。存在更好的时间戳格式。

所以最后,提取日期、月份和年份,然后单独比较它们可能是值得的。

【讨论】:

  • 我正在尝试使用 strptim 将字符串转换为时间,但由于某种原因它不喜欢我在函数中的最后一行,但我不确定为什么。 char* calcage(char **individual, char **age) { time_t time_raw_format;结构 tm * time_struct; char *生日 = (char *)malloc(50*sizeof(char));结构 tm * 出生解析;结构 tm * 出生结构; birthparse = strptime(生日, "%D",birth_struct); }
  • 过去,当我需要比 Unix 日期值更大的范围时,我使用儒略/天文日数。它允许在“我们的”日历中进行历史调整,并且具有大约公元前 4000 年的某个时间的纪元日期。 (我没有检查这是否与 Usher 的计算故意同步,但我假设是这样。)
猜你喜欢
  • 2013-10-31
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
相关资源
最近更新 更多