如何从ISO格式的日期中仅提取时间?我试过这个:
var d = new Date('1970-01-15T03:32:12.000Z'); //ISO-8601 formatted date returned from server
console.log(d.getTime());// 1222332000
预期的操作是:03:32:12
由于您的服务器返回具有预定义格式的ISO-8601格式化日期,您可以使用toISOString()
将其转换为ISO字符串,然后获取时间值的子字符串:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.toISOString().substr(11,8));
Date.getTime()
以UNIX纪元格式返回时间。 https://en.wikipedia.org/wiki/Unix_time
要仅访问您感兴趣的参数,可以使用Date.getMinutes()
,Date.getMinutes()
等。请参阅MDN上的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
注意:当您使用Date
的时间时,不要忘记在时区上花一点时间,特别是当您的应用程序在不同区域运行时。
您必须使用Date.prototype
方法手动构建时间字符串:getHours,getMinutes和getSeconds
或者使用moment.js库。
你可以使用getHours()
,getMinutes()
和getSecondes()
。然后您可以将它与字符串或对象一起使用。
请尝试以下方法:
d.toTimeString().split(' ')[0]
您可以使用moment.js来解析您喜欢的任何格式。
如果你认为moment.js太大了,还有另一个库调用dayjs。相同的时尚API,但只有2KB。 ( 不幸的是,你还不能用dayjs做UTC时间。 )
更新:感谢kun通知更新。从v1.8.9开始,您现在可以将UTC与dayjs插件一起使用。
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(moment(d).utc().format('HH:mm:ss'));
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs(d).utc().format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/plugin/utc.js"></script>