我有这个元素:
<v-text-field
label="Choose a time"
type="time"
mask="time"
step="1800"
prepend-inner-icon="access_time"
v-model="expiryTime"
:rules="[v => !!v || 'Time is required']"
required
@change="getTime"
></v-text-field>
我想触发getTime
方法将v-model
值转换为h:mm
格式。由于我一直在测试,我每次都输入12:00 pm
作为expiryTime
的值,并执行以下操作:
getTime(){
alert(moment().format('h:mm')) //returns current time in x:xx format
alert(this.expiryTime); // Returns '1200'
alert(moment(this.expiryTime).format('h:mm')); // returns '4:26, expect 12:00
alert(moment(this.expiryTime, 'h:mm')); // returns 'Sat Aug 17 2019 12:00:00 GMT-0600', expect 12:00
基本上我得到了一些意想不到的值,我不知道为什么。如果我可以在顶部警报中获取当前时间,我对如何以相同的方式格式化expiryTime
数据最终4:26
感到困惑。最终警报返回整个时间以及日期等。
有人可以解释一下如何正确将expiryTime
数据转换为h:mm格式吗?
moment(String)
构造函数采用 ISO 8601 字符串或RFC2822日期时间字符串。如果这两个标准均未使用,则必须将格式指定为构造函数的第二个参数。
expiryTime
(1200
(是hmm
的形式,但你指定了h:mm
,这需要在小时和分钟之间加上冒号,moment
才能正确解析日期。解决方法是删除冒号。
console.log(moment(1200, 'hmm').format('h:mm'))
console.log(moment(135, 'hmm').format('h:mm'))
console.log(moment(2001, 'hmm').format('h:mm'))
<script src="https://unpkg.com/moment@2.24.0/moment.js"></script>