关于时间:c ++将time_t转换为字符串,然后再次返回

c++ convert time_t to string and back again

我想将time_t转换为字符串然后再次返回。

我想使用ctime()将时间转换为字符串。

我似乎无法在Google或time.h标头文件中找到任何内容,有什么想法吗?

基本上,我想做的是将日期存储在文件中,然后将其读回,以便可以再次将其用作time_t。

另外,std,mfc之外没有库引用。

还有一点需要注意,这必须在Windows xp及更高版本上起作用,仅此而已。

编辑

我要做的就是将time_t转换为字符串(我不在乎它是否可读),然后将其转换回time_t。 我基本上只是想将time_t存储到文件中并再次读取(但是我不需要任何代码,因为除了time_t之外文件中还会有更多信息)。


您必须编写自己的函数才能执行此操作。这些函数将任何原始类型(或将operator <<和/或operator >>重载的任何类型)转换为字符串,反之亦然:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
std::string StringUtils::toString(const T &t) {
    std::ostringstream oss;
    oss << t;
    return oss.str();
}

template<typename T>
T StringUtils::fromString( const std::string& s ) {
    std::istringstream stream( s );
    T t;
    stream >> t;
    return t;
}


ctime()返回一个指向使用特定格式的字符缓冲区的指针。您可以使用sprintf()将这样的字符串解析为各个部分,将它们存储在struct tm中,然后使用mktime()将其转换为time_t


使用gmtime()将time_t转换为struct tm,然后使用strftime()将struct tm转换为纯文本(最好是ISO 8601格式)。结果将是便携式的,人类可读的和机器可读的。

要返回time_t,只需将字符串解析回结构tm并使用mktime()。


维基百科的time_t文章对此有所说明。底线是在C规范中不能保证time_t的类型。这是您可以尝试的示例:

尝试stringstream

1
2
3
4
5
6
7
8
9
#include <string>
#include <sstream>

time_t seconds;
time(&seconds);

std::stringstream ss;
ss << seconds;
std::string ts = ss.str();

Boost的lexical_cast是上述技术的一个很好的包装:

1
2
3
4
5
6
7
#include <boost/lexical_cast.hpp>
#include <string>

time_t t;
time(&t);

std::string ts = boost::lexical_cast<std::string>(seconds);

维基百科上的time_t:

The time_t datatype is a data type in
the ISO C library defined for storing
system time values. Such values are
returned from the standard time()
library function. This type is a
typedef defined in the standard
header. ISO C defines
time_t as an arithmetic type, but does
not specify any particular type,
range, resolution, or encoding for it.
Also unspecified are the meanings of
arithmetic operations applied to time
values.

Unix and POSIX-compliant systems implement the time_t type as a signed
integer
(typically 32 or 64 bits wide)
which represents the number of seconds
since the start of the Unix epoch:
midnight UTC of January 1, 1970 (not
counting leap seconds). Some systems
correctly handle negative time values,
while others do not. Systems using a
32-bit time_t type are susceptible to
the Year 2038 problem.