Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

c++ - How Do I Parse a Date Time String That Includes Fractional Time?

I have a date time string:

20:48:01.469 UTC MAR 31 2016

I would like to convert this string representation of time to a struct tm using strptime, but my format string isn't working.

Is there a format specifier for fractional seconds? Perhaps %S, %s, or something else?

Code snippet is below:

tm tmbuf;
const char *str = "20:48:01.469 UTC MAR 31 2016"
const char *fmt = "%H:%M:%s %Z %b %d %Y";
strptime(str,fmt,&tmbuf);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using this free, open source C++11/14 library, here is another way to deal with parsing fractional seconds:

#include "tz.h"
#include <iostream>
#include <sstream>

int main()
{
    using namespace date;
    using namespace std::chrono;
    std::istringstream str("20:48:01.469 UTC MAR 31 2016");
    sys_time<milliseconds> tp;
    parse(str, "%T %Z %b %d %Y", tp);
    std::cout << tp << '
';
}

Output:

2016-03-31 20:48:01.469

I.e., with this tool %S and %T just work. The precision is controlled not with flags, but with the precision of the std::chrono::time_point.

If you want to find out what timezone abbreviation you parsed, that is also possible:

std::istringstream str("20:48:01.469 UTC MAR 31 2016");
sys_time<milliseconds> tp;
std::string abbrev;
parse(str, "%T %Z %b %d %Y", tp, abbrev);
std::cout << tp << ' ' << abbrev << '
';

Output:

2016-03-31 20:48:01.469 UTC

This being said, this library is built on top of std::get_time and thus has the same portability problem that Jonathan's excellent (and upvoted) answer alludes to: Only libc++ currently parses month names in a case-insensitive manner. Hopefully that will change in the not-too-distant future.

libstdc++ bug report.

VSO#232129 bug report.

If you have to deal with timezones other than UTC, in general, there is no sure-fire method to do that, because at any one time, more than one timezone can be using the same abbreviation. So the UTC offset can be ambiguous. However here is a short article on how to use this library to narrow down an abbreviation to a list of candidate timezones from which you might have some ad hoc logic for choosing a unique timezone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...