Android系统日历事件以RFC2445标准解析duration参考代码
读取到的日历事件,duration按照RFC2445标准解析成准确时长
最近在做系统日历读取功能,发现duration字段以RFC2445标准设置的,各厂商应用的格式不一定一致。比如同样是一小时,有的用P1H代表一小时,有的用的P3600S代表3600秒,也是一小时。
所以根据标准,写了个解析范例方法,目前已经上线用了一段时间,没有发现问题。
方法解析出时长返回单位是秒(s)
private int parseDuration(String duration) {
if (duration.length() < 3) {
return 0;
}
String time = duration;
Log.d(TAG, "parse rfc2445 duration:" + duration);
if (duration.startsWith("P")) {
time = duration.substring(1);
}
int day = 0;
int week = 0;
int hour = 0;
int minute = 0;
int second = 0;
try {
do {
int index = time.indexOf("T");
if (index > 0) {//PxxT
if (time.charAt(index - 1) == 'D') {//PxxDT
day = Integer.parseInt(time.substring(0, index - 1));
}
if (index == time.length() - 1) {
break;
}
time = time.substring(index + 1);
} else {
index = time.indexOf("D");
if (index > 0) {//PxxD
day = Integer.parseInt(time.substring(0, index));
if (index == time.length() - 1) {
break;
}
time = time.substring(index + 1);
}
}
index = time.indexOf("W");
if (index > 0) {
week = Integer.parseInt(time.substring(0, index));
if (index == time.length() - 1) {
break;
}
time = time.substring(index + 1);
}
index = time.indexOf("H");
if (index > 0) {
hour = Integer.parseInt(time.substring(0, index));
if (index == time.length() - 1) {
break;
}
time = time.substring(index + 1);
}
index = time.indexOf("M");
if (index > 0) {
minute = Integer.parseInt(time.substring(0, index));
if (index >= time.length() - 1) {
break;
}
time = time.substring(index + 1);
}
index = time.indexOf("S");
if (index > 0) {
second = Integer.parseInt(time.substring(0, index));
}
} while (false);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "cannot parse duration:" + duration);
}
day += 7 * week;
hour += day * 24;
minute += hour * 60;
second += minute * 60;
return second;
}