将秒转换为毫秒 - javascript

问题描述 投票:0回答:3

我今天刚刚开始学习 javascript,我正在尝试弄清楚如何将秒转换为毫秒。

我试图找到一些对我有帮助的东西,但我找到的所有东西都是将毫秒转换为分钟或小时。

let str = 'You must wait 140 seconds before changing hands';
let timer = 0;
let num = str.match(/\d/g).join("");
timer = num;

console.log(timer);

setTimeout(() => {
  console.log('time done')
}, timer);

我正在尝试从字符串中提取数字并将其转换为毫秒以设置超时。

javascript
3个回答
2
投票
  • 这是一个更好的正则表达式
    /(\d+) seconds?/
    -
    ?
    表示
    s
    是可选的
  • 正如这个词告诉我们的那样,1 秒是 1000 毫秒

let str = 'You must wait 140 seconds before changing hands';
let timer = str.match(/(\d+) seconds?/)[1]*1000; // grab the captured number and multiply by 1000
console.log(timer)
setTimeout(() => {
  console.log('time done')
}, timer);

这里是倒计时

let str = 'You must wait 10 seconds before changing hands';
const span = document.getElementById("timer");
let tId = setInterval(() => {
  let timeLeft = +str.match(/(\d+) seconds?/)[1]; // optional s on seconds
  if (timeLeft <= 1) {
    str = "Time's up";
    clearInterval(tId);
  }  
  else str = str.replace(/\d+ seconds?/,`${--timeLeft} second${timeLeft == 1 ? "" : "s"}`)
  span.innerHTML = str;
}, 1000);
<span id="timer"></span>


1
投票
let str = 'You must wait 140 seconds before changing hands';
let seconds = /\d+/.exec(str)[0];
// milliseconds = seconds * 1000;
const ms = seconds * 1000;

setTimeout(
 () => {// doSomething},
 ms
);
``


0
投票

如果您获取的时间戳以秒为单位,请将其转换为毫秒,以便您可以更改日期格式。

示例

let secToMilliSec = new Date(1551268800 * 1000);
let millToDate = new Date(secToMilliSec);
// Wed Feb 27 2019 17:30:00 GMT+0530 (India Standard Time)
© www.soinside.com 2019 - 2024. All rights reserved.