【问题标题】:Javascript Count-Up timer from timestamp in row's columnJavascript Count-Up timer 从行列中的时间戳
【发布时间】:2020-03-30 18:02:20
【问题描述】:

我有一个 MVC C# Web 应用程序,它有一个索引视图和一个表,该表在 UTC 时间格式的行中有条目。

我不想显示输入的时间,而是使用 javascript 从输入的时间开始计数。我可以用剃刀语法来做到这一点,但它只在页面刷新时更新。

保存时间戳的列有一个“计数器”类的元素。

我的问题是,setinterval 去哪里了,有没有一种快速简便的方法来做到这一点?我看过一些帖子,但大多数都是同时启动所有计时器,那么如何将计时器的“开始”值传递给函数并使用 setinterval?

这是表格 html。非常感谢任何帮助!

<table class="table">
<tbody><tr>
    <th>Name</th>
    <th>Time</th>
</tr>
<tr>
    <td>Joe Smith</td>
    <td><span class="Counter">3/30/2020 5:34:21 PM</span></td>
</tr>
<tr>
    <td>Ray Parker</td>
    <td><span class="Counter">3/30/2020 5:32:56 PM</span></td>
</tr>
<tr>
    <td>Jack Black</td>
    <td><span class="Counter">3/30/2020 5:32:16 PM</span></td>
</tr>

【问题讨论】:

    标签: javascript c# model-view-controller


    【解决方案1】:

    所以你的意思是你想显示像this is created 34 seconds ago

    没有像这样显示的原生 api。你必须自己做一个。

    // makes milliseconds to easy-readable string
    const formatDateTime = ms => {
      const sec = Math.floor(ms / 1000)
      if (sec < 60) return `${sec} seconds`
      const min = Math.floor(sec / 60)
      if (min < 60) return `${min} minutes`
      const hr = Math.floor(min / 60)
      if (hr < 24) return `${hr} hours`
      const day = Math.floor(hr / 24)
      if (day < 7) return `${day} days`
      const week = Math.floor(day / 7)
      return `${week} weeks`
    }
    
    const getTimeElapsed = from => {
      const previous = new Date(from);
      const now = new Date(); // get current datetime
      const comparedTime = (now.valueOf() - previous.valueOf());
      // get compared time in "milliseconds"
    
      return formatDateTime(comparedTime)
    }
    
    setInterval(() => {
      const str = getTimeElapsed('3/30/2020 7:10:16 PM')
      console.log(str)
    }, 1000)
    

    自行在 HTML 中插入代码。

    【讨论】:

    • 排序,但在视图中的 javascript.. 主要是为了显示自项目进入列表以来的实时计数/时间(以秒为单位)。因此,计数器列跨度将显示“00:16”或“4:16”。
    • 只需编辑我的formatDateTime 函数。这就是你格式化字符串的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多