【问题标题】:libssh2 remote file attributes last modification time with wrong timezonelibssh2远程文件属性上次修改时间错误的时区
【发布时间】:2016-11-10 14:26:38
【问题描述】:

我在linux 上使用libssh2C++

我打算在从 sftp 下载文件之前查看上次修改时间。

为此,我使用以下命令:

LIBSSH2_SFTP_ATTRIBUTES attrs;
libssh2_sftp_fstat_ex(sftp_handle, &attrs, 0);

我使用attrs.mtime 获得最后修改时间,这是一个long 类型,给出秒数。

但是,此值适用于时区 GMT+0。我怎样才能得到我当地时区的时间?

谢谢。

【问题讨论】:

    标签: c++ linux libssh2


    【解决方案1】:

    C 标准库对时区转换函数的支持很糟糕。 但简而言之,假设 tzname 变量设置正确,您可以执行以下操作。

    struct tm tm_utc;
    gmtime_r(&attrs.mtime, &tm_utc);  // Converts from epoch time_t to utc struct.   
    time_t local_time = mktime(&tm_utc);  // converts from time struct back to time_t in local time.
    
    printf("local timezone %s, difference %ld\n", *tzname, attrs.mtime - local_time);
    

    请注意,mktime 在内部调用 tzset,然后使用时区信息将时间转换为正确的时区。 tzset 读取 TZ 环境变量,这就是系统知道使用哪个时区的方式。

    【讨论】:

    • 谢谢。但是你不考虑sftp(libssh2库),这是问题的核心。 sftp 服务器提供的文件属性中的时间变量已经以秒为单位,不包括时区信息。你知道我怎么能得到这个吗?
    • 我不确定我是否理解。您写道 attrs.mtime 是 GMT 时间,并且您想将其转换为 您的 时区。好像和sftp服务器没有关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2021-10-08
    • 2012-12-08
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多