2016-07-06 22 views
1

有一個輸入字段,其時間爲hh:mm。javascript返回最近的季度的時間

具有如下功能的任何一個

  1. 檢查正確的時間語法。

  2. 更改爲:如果還有其他問題,例如。分隔小時和分鐘輸入.,;

  3. 格式化時間到最近的15分鐘。例如。 05 - > 00 08 - > 15

編輯: 輸入來源於此:

<input name=event_time_end id=event_time_end type=text maxlengt=5 size=5 value='' onblur='toTime(this);'> 

問候

回答

1

將該溶液強制語法,去除多餘的字符,並格式化該結果作爲有效時間:

console.clear(); 
 
function closestQuarter(n) { 
 
\t return (Math.round(n % 60/15) * 15) % 60; 
 
} 
 
function toTime(str) { 
 
\t str = str 
 
\t \t //Replace non-digist with ':' 
 
\t \t .replace(/(?:\D*)?\D+/g, ':') 
 
\t \t //Replace first ':' with '*' to give us a target 
 
\t \t .replace(':', '*') 
 
\t \t //Remove ':' 
 
\t \t .replace(/:/g, '') 
 
\t \t //Split by '*' 
 
\t \t .split('*'); 
 
\t //In case of empty string 
 
\t if (str.length < 1) { 
 
\t \t str.push('00'); 
 
\t } 
 
\t //In case of only hours 
 
\t if (str.length < 2) { 
 
\t \t str.push('00'); 
 
\t } 
 
\t for (var i = 0; i < str.length; i++) { 
 
\t \t if (str[i].length > 2) { 
 
\t \t \t str[i] = str[i].substr(0, 2); 
 
\t \t } 
 
\t \t if (str[i].length == 0) { 
 
\t \t \t str[i] = '00'; 
 
\t \t } 
 
\t } 
 
\t //Force 0-23 
 
\t str[0] = (parseInt(str[0]) % 24).toString(); 
 
\t //Round to quarter 
 
\t str[1] = closestQuarter(parseInt(str[1])).toString(); 
 
\t //Prepend '0' if needed 
 
\t for (var i = 0; i < str.length; i++) { 
 
\t \t if (str[i].length < 2) { 
 
\t \t \t str[i] = '0' + str[i]; 
 
\t \t } 
 
\t } 
 
\t //Return a ':' joined string 
 
\t return str.join(':') 
 
} 
 
//Tests 
 
console.log([toTime('21:45'), 
 
\t \t toTime('21:4'), 
 
\t \t toTime('1:3'), 
 
\t \t toTime('1.3'), 
 
\t \t toTime('1.3i3'), 
 
\t \t toTime('13.37pm') 
 
\t ]); 
 

 
function displayInHTML() { 
 
\t //Get value from element 
 
\t var input = (document.getElementById("time").value).toString(); 
 
\t var output = document.getElementById("output"); 
 
\t output.innerHTML = toTime(input); 
 
}
<input type="text" id="time" name="time" onkeyup="displayInHTML()"/> 
 
<textarea style="width:100%" id="output" readonly></textarea>

+0

奇怪。運行代碼片段 - 沒有錯誤。複製粘貼 - TypeError:str.join不是函數 – osomanden

+0

什麼瀏覽器和瀏覽器版本? –

+0

FireFox版本47.0.1 只是爲了驗證 - alert(str)和alert(str [1])給出了「object HTMLInputElement」 – osomanden

0

爲了圓一個數分鐘到最近的季度中,你可以使用:

var x = minutes + 7; 
minutes = x - (x % 15) 

var minutes, x; 
 
for (minutes = 0; minutes <= 50; minutes++) { 
 
    x = minutes + 7; 
 
    console.log(minutes + ' : ' + (x - (x % 15))); 
 
}

2

您可以通過15分分鐘,用15乘以舍入結果爲正確的季度。

var minutes; 
 

 
for (minutes = 0; minutes < 60; minutes++) { 
 
    console.log(minutes + ': ' + (Math.round(minutes/15) * 15)); 
 
}