如何解析目标C中的ISO-8601持续时间? [英] How to parse an ISO-8601 duration in Objective C?

查看:101
本文介绍了如何解析目标C中的ISO-8601持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来解析在Objective C中包含ISO-8601 持续时间的字符串。结果应该是像 NSTimeInterval

I'm looking for an easy way to parse a string that contains an ISO-8601 duration in Objective C. The result should be something usable like a NSTimeInterval.

ISO-8601持续时间的一个例子: P1DT13H24M17S ,这意味着1天, 13小时24分17秒。

An example of an ISO-8601 duration: P1DT13H24M17S, which means 1 day, 13 hours, 24 minutes and 17 seconds.

推荐答案

如果您确切知道要获得哪些字段,可以使用一个调用 sscanf()

If you know exactly which fields you'll be getting, you can use one invocation of sscanf():

const char *stringToParse = ...;
int days, hours, minutes, seconds;
NSTimeInterval interval;
if(sscanf(stringToParse, "P%dDT%dH%dM%sS", &days, &hours, &minutes, &seconds) == 4)
    interval = ((days * 24 + hours) * 60 + minutes) * 60 + seconds;
else
    ; // handle error, parsing failed

如果任何字段可能被省略,您需要在你的解析中有点聪明,例如:

If any of the fields might be omitted, you'll need to be a little smarter in your parsing, e.g.:

const char *stringToParse = ...;
int days = 0, hours = 0, minutes = 0, seconds = 0;

const char *ptr = stringToParse;
while(*ptr)
{
    if(*ptr == 'P' || *ptr == 'T')
    {
        ptr++;
        continue;
    }

    int value, charsRead;
    char type;
    if(sscanf(ptr, "%d%c%n", &value, &type, &charsRead) != 2)
        ;  // handle parse error
    if(type == 'D')
        days = value;
    else if(type == 'H')
        hours = value;
    else if(type == 'M')
        minutes = value;
    else if(type == 'S')
        seconds = value;
    else
        ;  // handle invalid type

    ptr += charsRead;
}

NSTimeInterval interval = ((days * 24 + hours) * 60 + minutes) * 60 + seconds;

这篇关于如何解析目标C中的ISO-8601持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆