我正在尝试将我在计时器中使用的时间转换为HH:MM:SS格式使用Moment Js,但被卡住了。以下是我的代码。
<iron-timer id="timer" start-time="150" end-time="0" current-time="[[currentTime]]">
<moment-js date="[[_calculatedTime(currentTime)]]"></moment-js>
</iron-timer>
因此,当时间开始时,时间不会在格式化日期中更新。我该如何工作
这是我想到的,但是您的问题有些不完整,所以如果我走错的方式,请纠正我。
组件依赖性:聚合物2.5,铁接手2.1.2,Moment-JS 0.7.2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Timer</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-timer/iron-timer.html">
<link rel="import" href="../bower_components/moment-js/moment-js.html">
</head>
<body>
<dom-module id="moment-timer">
<template>
<iron-timer id="timer" start-time="150" end-time="0" current-time="{{currentTime}}"></iron-timer>
<moment-js date="[[_toMilliSecs(currentTime)]]" format="HH:mm:ss" utc></moment-js>
</template>
<script>
class MomentTimer extends Polymer.Element{
static get is(){
return 'moment-timer';
}
static get properties(){
return {
currentTime: Number
}
}
_toMilliSecs(currentTime){
return currentTime * 1000;
}
ready(){
super.ready();
this.$.timer.start();
}
}
window.customElements.define(MomentTimer.is,MomentTimer);
</script>
</dom-module>
<moment-timer></moment-timer>
</body>
</html>
有几件事要注意:
- 您必须在脚本中的某个地方启动计时器。我在Ready((回调中做到了这一点。确保首先致电
super.ready()
。 - 您需要将
currentTime
属性作为毫秒传递到moment-js
元素 - 我使用方法_toMilliSecs
来做到这一点。 - 如Moment-JS中的一个演示示例中所示,您需要在
moment-js
元素上设置utc
属性。这是为您的计数提供的开始参考所必需的。本质上,我们将其计算为从1970-01-01 00:00:00开始的时间,并将计时器相对于此设置。效果是相同的。
希望有帮助!