解析CalendarContract.Events.DURATION值

时间:2015-06-17 11:53:51

标签: android android-calendar

我正在查询我的日历并显示所有事件结果。 当我试图解析值CalendarContract.Events.DURATION时,我得到一个RFC2445字符串格式。

例如,我得到了“P15M”,我知道这是15分钟的会议。 在互联网上挖掘如何解析RFC2445之后我发现了一些google jar here

但是有没有任何静态类来解析这些格式? 编译一个jar并仅将其用于1个函数,这不是那么好......

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

我遇到了和你一样的问题,挖了一遍,发现了以下有用的片段。我重构了一下,所以它会更具可读性。希望它有所帮助!

 public static long RFC2445ToMilliseconds(String str)
{


    if(str == null || str.isEmpty())
        throw new IllegalArgumentException("Null or empty RFC string");

    int sign = 1;
    int weeks = 0;
    int days = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;

    int len = str.length();
    int index = 0;
    char c;

    c = str.charAt(0);

    if (c == '-')
    {
        sign = -1;
        index++;
    }

    else if (c == '+')
        index++;

    if (len < index)
        return 0;

    c = str.charAt(index);

    if (c != 'P')
        throw new IllegalArgumentException("Duration.parse(str='" + str + "') expected 'P' at index="+ index);

    index++;
    c = str.charAt(index);
    if (c == 'T')
        index++;

    int n = 0;
    for (; index < len; index++)
    {
        c = str.charAt(index);

        if (c >= '0' && c <= '9')
        {
            n *= 10;
            n += ((int)(c-'0'));
        }

        else if (c == 'W')
        {
            weeks = n;
            n = 0;
        }

        else if (c == 'H')
        {
            hours = n;
            n = 0;
        }

        else if (c == 'M')
        {
            minutes = n;
            n = 0;
        }

        else if (c == 'S')
        {
            seconds = n;
            n = 0;
        }

        else if (c == 'D')
        {
            days = n;
            n = 0;
        }

        else if (c == 'T')
        {
        }
        else
            throw new IllegalArgumentException ("Duration.parse(str='" + str + "') unexpected char '" + c + "' at index=" + index);
    }

    long factor = 1000 * sign;
    long result = factor * ((7*24*60*60*weeks)
            + (24*60*60*days)
            + (60*60*hours)
            + (60*minutes)
            + seconds);

    return result;
}

答案 1 :(得分:1)

在游标的while循环中

  

字符串持续时间=&#34;您的持续时间&#34 ;;

        try {
            Duration d = new Duration();
            d.parse(duration);
            endMillis = startMillis + d.getMillis();
            if (debug)
                Log.d(TAG, "startMillis! " + startMillis);
            if (debug)
                Log.d(TAG, "endMillis!   " + endMillis);
            if (endMillis < startMillis) {
                continue;
            }
        } catch (DateException e) {
            if (debug)
                Log.d(TAG, "duration:" + e.toString());
            continue;
        }

The class Duration isalso refer行号1487.有解析逻辑,您只需要在源代码中包含持续时间类,并像在try块中一样进行解析。

我希望它有所帮助