【问题标题】:Get and save the date in a struct C在结构 C 中获取并保存日期
【发布时间】:2018-01-27 18:48:11
【问题描述】:

我有这样的事情:

void set_email_date()
{
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    strcpy(email.date, tm.tm_mday"-"tm.tm_month+1"-"tm.tm_year +1900);
}

我知道这是非常错误的,但我尝试了 1000 种不同的想法,但都没有奏效。 我想按照这个结构存储它dd-mm-yyyy

【问题讨论】:

  • 你试过strftime吗?
  • 使用snprintf
  • “我已经尝试了 1000 种不同的想法”,只发布了 1 条不可编译的想法。

标签: c date struct char


【解决方案1】:
tm.tm_mday"-"tm.tm_month+1"-"tm.tm_year +1900

这不是你创建字符串的方式。

char date[100];
sprintf(date, "%02d-%02d-%d\n", tm.tm_day, tm.tm_mon + 1, tm.tm_year + 1900);
strcpy(email.date, date);

只有当email.date 是一个有足够空间的数组或者如果你 已经与malloc 和朋友动态分配内存。没有 看看你是怎么做到的,这只是一个猜测。

但您也可以使用strftime 来格式化日期。

man strftime

#include <time.h>

size_t strftime(char *s, size_t max, const char *format,
                       const struct tm *tm);

描述

strftime()函数根据格式规范格式化分解时间tm,并将结果放入字符中 大小为max 的数组。分解时间结构 tm 在&lt;time.h&gt; 中定义。另见ctime(3)

因为我们不知道您是如何初始化 email.date 的 类型,我会假设这是 char[20] 或其他东西。

strftime(email.date, sizeof email.date, "%d-%m-%Y", &tm);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多