jquery 将时间转换为倒计时器剩余时间的字

s6fujrry  于 2023-02-18  发布在  jQuery
关注(0)|答案(1)|浏览(140)

我已经找了一整天把时间转换成文字,但没有找到任何东西。
我有一个计时器,记录开始时间和结束时间--之后我显示用户还有多少时间。
下面是x1c 0d1x示例
我想把时间余额转换成文字;预期产出应为:
4分49秒

63lcw9qa

63lcw9qa1#

这里是一个简单的时间到字转换器。
convert()函数是取输入并识别时间,同时,convertNumber2Word()函数是将任意数字转换为字。
通过结合这两个功能,你将能够得到你想要的结果。

function convert(){
  //For your case, you may get the time value directly from the element that contain it. Eg. time = document.getElementById("targetID").textContent;
  const time = document.getElementById("time").value;
  const splitTime = time.split(":");
  const minute = Number(splitTime[0]);
  const second = Number(splitTime[1]);
  const convertedText = `${convertNumber2Word(minute)} minute${minute>1?"s":""} and ${convertNumber2Word(second)} second${second>1?"s":""}`;
  document.getElementById("result").textContent = convertedText;
}

function convertNumber2Word(number){
  let oneToTwenty = ['','one ','two ','three ','four ','five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '], tenth = ['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'];
  if(number.toString().length > 7){return console.log("out of range");}
  let num = ('0000000'+ number).slice(-7).match(/^(\d{1})(\d{1})(\d{2})(\d{1})(\d{2})$/);
  if(!num) return;
  let outputText = num[1] != 0 ? (oneToTwenty[Number(num[1])] || `${tenth[num[1][0]]} ${oneToTwenty[num[1][1]]}` )+' million ' : ''; 
  outputText +=num[2] != 0 ? (oneToTwenty[Number(num[2])] || `${tenth[num[2][0]]} ${oneToTwenty[num[2][1]]}` )+'hundred ' : ''; 
  outputText +=num[3] != 0 ? (oneToTwenty[Number(num[3])] || `${tenth[num[3][0]]} ${oneToTwenty[num[3][1]]}`)+' thousand ' : ''; 
  outputText +=num[4] != 0 ? (oneToTwenty[Number(num[4])] || `${tenth[num[4][0]]} ${oneToTwenty[num[4][1]]}`) +'hundred ': ''; 
  outputText +=num[5] != 0 ? (oneToTwenty[Number(num[5])] || `${tenth[num[5][0]]} ${oneToTwenty[num[5][1]]} `) : ''; 
  return outputText;
}
#result:first-letter {
  text-transform: uppercase;
}
<div>Enter Time: (XX:XX)</div>
<input id="time" placeholder="XX:XX" value="04:49">
<button onclick="convert()">Convert to text</button>
<div id="result"><div>

参考:Number to word conversion function

相关问题