C++ 日期/时间转换:字符串表示到 time_t
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/321793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date/time conversion: string representation to time_t
提问by An???drew
How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS"
, to a time_t
value in either C or C++?
如何转换日期字符串,格式为"MM-DD-YY HH:MM:SS"
,在time_t
值用C或C ++?
回答by Robert Gamble
Use strptime()
to parse the time into a struct tm
, then use mktime()
to convert to a time_t
.
用于strptime()
将时间解析为struct tm
,然后用于mktime()
转换为time_t
。
回答by Rob
In the absence of strptime
you could use sscanf
to parse the data into a struct tm
and then call mktime
. Not the most elegant solution but it would work.
在没有的情况下,strptime
您可以使用sscanf
将数据解析为一个struct tm
然后调用mktime
. 不是最优雅的解决方案,但它会起作用。
回答by Rob
Boost's date time library should help; in particular you might want to look at http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/date_time_io.html
Boost 的日期时间库应该会有所帮助;特别是你可能想看看http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/date_time_io.html
回答by Johannes Schaub - litb
I'm afraid there isn't any in Standard C / C++ . There is the POSIX function strptime
which can convert to struct tm
, which can then be converted to time_t
using mktime
.
恐怕标准 C / C++ 中没有。有 POSIX 函数strptime
可以转换为struct tm
,然后可以转换为time_t
使用mktime
.
If you are aiming for cross platform compatibility, better use boost::date_time
, which has sophisticated functions for this.
如果您的目标是跨平台兼容性,请更好地使用boost::date_time
,它为此具有复杂的功能。
回答by Shital Shah
Note that strptime
mentioned in accepted answer is not portable. Here's handy C++11 code I use to convert string to std::time_t :
请注意,strptime
接受的答案中提到的内容不可移植。这是我用来将字符串转换为 std::time_t 的方便的 C++11 代码:
static std::time_t to_time_t(const std::string& str, bool is_dst = false, const std::string& format = "%Y-%b-%d %H:%M:%S")
{
std::tm t = {0};
t.tm_isdst = is_dst ? 1 : 0;
std::istringstream ss(str);
ss >> std::get_time(&t, format.c_str());
return mktime(&t);
}
You can call it like this:
你可以这样称呼它:
std::time_t t = to_time_t("2018-February-12 23:12:34");
You can find string format parameters here.
您可以在此处找到字符串格式参数。
回答by chux - Reinstate Monica
best way to convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t
将格式为“MM-DD-YY HH:MM:SS”的日期字符串转换为 time_t 的最佳方法
Restricting code to standard C library functions is looking for the inverse of strftime()
. To expand @Robgeneral idea, uses sscanf()
.
将代码限制为标准 C 库函数正在寻找strftime()
. 要扩展@Rob 的总体思路,请使用sscanf()
.
Use "%n"
to detect completed scan
使用"%n"
到检测完成的扫描
time_t date_string_to_time(const char *date) {
struct tm tm = { 0 }; // Important, initialize all members
int n = 0;
sscanf(date, "%d-%d-%d %d:%d:%d %n", &tm.tm_mon, &tm.tm_mday, &tm.tm_year,
&tm.tm_hour, &tm.tm_min, &tm.tm_sec, &n);
// If scan did not completely succeed or extra junk
if (n == 0 || date[n]) {
return (time_t) -1;
}
tm.tm_isdst = -1; // Assume local daylight setting per date/time
tm.tm_mon--; // Months since January
// Assume 2 digit year if in the range 2000-2099, else assume year as given
if (tm.tm_year >= 0 && tm.tm_year < 100) {
tm.tm_year += 2000;
}
tm.tm_year -= 1900; // Years since 1900
time_t t = mktime(&tm);
return t;
}
Additional code could be used to insure only 2 digit timestamp parts, positive values, spacing, etc.
附加代码可用于确保只有 2 位时间戳部分、正值、间距等。
Note: this assume the "MM-DD-YY HH:MM:SS" is a localtime.
注意:这里假设“MM-DD-YY HH:MM:SS”是当地时间。
回答by hmehdi
static time_t MKTimestamp(int year, int month, int day, int hour, int min, int sec)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = gmtime ( &rawtime );
timeinfo->tm_year = year-1900 ;
timeinfo->tm_mon = month-1;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = min;
timeinfo->tm_sec = sec;
timeinfo->tm_isdst = 0; // disable daylight saving time
time_t ret = mktime ( timeinfo );
return ret;
}
static time_t GetDateTime(const std::string pstr)
{
try
{
// yyyy-mm-dd
int m, d, y, h, min;
std::istringstream istr (pstr);
istr >> y;
istr.ignore();
istr >> m;
istr.ignore();
istr >> d;
istr.ignore();
istr >> h;
istr.ignore();
istr >> min;
time_t t;
t=MKTimestamp(y,m,d,h-1,min,0);
return t;
}
catch(...)
{
}
}