简体   繁体   中英

C++ convert “HH:MM:SS.fraction” to int64_t

在C或C ++中是否有一种通用,方便,跨平台的方法将格式字符串“HH:MM:SS。<一小部分>”转换为(timedelta)数字类型,反之亦然?

strptime is as portable as it gets for this particular problem. It is not in the C standard library (even if it had been added since C89, C99 and C2011 are no more portable than POSIX (thanks ever so much, Microsoft)) but it's widespread enough that my recommendation is to write your code as if it were universal, then detect its absence in your build system and inject a replacement. You can get a BSD-licensed replacement here: http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD (may require portability tweakage)

It is not TERRIBLY hard (I'm assuming your time is machine generated, not hand-written, so we can rely on it being "correct" - otherwise, we'd have to add a load of "is this value in range" checks). I'm also going to assume that fraction is always the same number of digits.

int64_t parsetime(char *str)
{
    int hh, mm, ss, fract;
    int64_t t;

    if (sscanf(str, "%d:%d:%d.%d", &hh, &mm, &ss, &fract) != 4)
    {
        printf("Badly formed time %s\n", str);
        return -1;
    }

    // 1000000 assumes there are 6 digits in fract, and we want microseconds.
    t = ((hh * 60)  + mm *60) + s) * 1000000 + fract;

    return t;
}

You could do something similar, using a double and %d:%d:%lf for the format string, then multiply by the releveant multiplier to get your fractions into integer form (eg 1000 for milliseconds, 1000000 for micro, 100000000 for nanoseconds, etc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM