【问题标题】:C: string to milisecs timestampC:字符串到毫秒时间戳
【发布时间】:2016-06-05 13:58:27
【问题描述】:

我想在函数中以字符串格式从时间戳返回 time_t 值,但我不明白。我需要帮助。

我读取一个Redis数据库的字符串KEY,它是一个时间戳值,形式为,例如“1456242904.226683”

我的代码是:

time_t get_ts(redisContext *ctx)
{
    redisReply *reply;
    reply = redisCommand(ctx, "GET %s", "KEY");
    if(reply == NULL){
        return -1;
    }

    char error[255];
    sprintf(error, "%s", "get_ts 2:",reply->str);
    send_log(error);

    freeReplyObject(reply);

    return reply->str;
}

reply->str 是一个字符串值,但我需要返回一个 time_t 值。

我该怎么做?

谢谢

【问题讨论】:

  • freeReplyObject() 之后,您无论如何都不能return 成为会员......
  • 对@sourav-ghosh。哎呀!对不起。我试图继续我的问题。 ô_Ô

标签: c redis timestamp time-t


【解决方案1】:

我假设 1456242904.226683 是自 1970 年 1 月 1 日 00:00 以来的秒数。这大约是 46 年。 1456242904.226683 是浮点值,time_t 是整数数据类型。 您无法将 1456242904.226683 准确地转换为 time_t,但您可以转换 1456242904。 首先使用atof将字符串转换为浮点值, 然后将浮点值转换为time_t

#include <stdlib.h>     // atof

time_t get_ts(redisContext *ctx)
{
    redisReply *reply;
    reply = redisCommand(ctx, "GET %s", "KEY");
    if(reply == NULL){
        return -1;
    }

    char error[255];
    sprintf(error, "%s", "get_ts 2:",reply->str);
    send_log(error);

    time_t t = (time_t)atof(reply->str);
             // ^^^^^^ ^^^^

    freeReplyObject(reply);

    return t;
}

【讨论】:

  • Rabbid,您的解决方案几乎完美:) 我的回复->str 变量的格式为 1456242904.226683 但 (time_t) atof(reply->str) 仅返回 1456242904 我不明白。怎么了?谢谢!
  • @Lamujeresponja 正如我试图在我的回答中解释的那样。 time_t 是一个整数数据类型。不能保留小数点后的数字。
  • 是的,对不起。我的英语很差。然后,现在我找到了获得毫秒转换的解决方案。非常感谢你的帮助。来自西班牙的问候。埃尔维拉
猜你喜欢
  • 1970-01-01
  • 2018-09-02
  • 2016-08-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2011-10-07
  • 1970-01-01
相关资源
最近更新 更多