在考虑了这里的反馈之后,我决定实现一个具有简洁输入样式和一些智能解析的表单字段。有关最终结果,请参见http://jsfiddle.net/davesag/qgCrk/6/。当然欢迎改进。
function to_seconds(dd,hh,mm) {
d = parseInt(dd);
h = parseInt(hh);
m = parseInt(mm);
if (isNaN(d)) d = 0;
if (isNaN(h)) h = 0;
if (isNaN(m)) m = 0;
t = d * 24 * 60 * 60 +
h * 60 * 60 +
m * 60;
return t;
}
// expects 1d 11h 11m, or 1d 11h,
// or 11h 11m, or 11h, or 11m, or 1d
// returns a number of seconds.
function parseDuration(sDuration) {
if (sDuration == null || sDuration === '') return 0;
mrx = new RegExp(/([0-9][0-9]?)[ ]?m/);
hrx = new RegExp(/([0-9][0-9]?)[ ]?h/);
drx = new RegExp(/([0-9])[ ]?d/);
days = 0;
hours = 0;
minutes = 0;
if (mrx.test(sDuration)) {
minutes = mrx.exec(sDuration)[1];
}
if (hrx.test(sDuration)) {
hours = hrx.exec(sDuration)[1];
}
if (drx.test(sDuration)) {
days = drx.exec(sDuration)[1];
}
return to_seconds(days, hours, minutes);
}