【问题标题】:Visual C++ how to convert Datetime to number of seconds since 1970Visual C++ 如何将日期时间转换为自 1970 年以来的秒数
【发布时间】:2013-05-02 06:28:52
【问题描述】:

我正在尝试转换日期时间: http://msdn.microsoft.com/en-us/library/03ybds8y

自 1970 年以来使用 Visual C++ 的秒数。

我搜索了许多解决方案,但无法使它们中的任何一个起作用。 谢谢

【问题讨论】:

    标签: visual-c++ datetime seconds


    【解决方案1】:

    您可以使用两个日期之间的差异TimeSpan 来执行此操作。像这样的:

    DateTime dtDateYouWantToConvert = /* .... */
    DateTime dtReference(1970, 1, 1, 0, 0, 0);
    
    TimeSpan tsDiff = dtDateYouWantToConvert - dtReference;
    
    // calculate number of seconds (including fractional) since 1/1/1970
    double dSeconds = tsDiff.TotalSeconds;
    

    【讨论】:

    • 您好,谢谢您的回答。
    • 另一个小问题,如何将秒数转换回字符串形式的时间?我的意思是从 dSeconds 回到 DateTime?
    • 只需将TimeSpan 添加(或减去)到DateTime,您将得到一个DateTime,您可以格式化,或使用TimeSpan.ToString(format) 获取TimeSpan 的字符串.
    • 如何将秒数转换为日期时间?
    • 我找到了一个有效的答案,我不知道是否有更简单的东西:time_t ts;双 dSeconds = tsDiff.TotalSeconds; ts = (time_t) dSeconds;结构 tm *tm_ts = gmtime(&ts);字符 str_temp44 [80] = ""; strftime (str_temp44, 80, "%a, %d.%m.%Y %H:%M:%S", tm_ts);
    猜你喜欢
    • 2011-08-31
    • 2023-01-08
    • 2012-01-19
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2013-01-20
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多