我有以下 JSON 字符串,我想从中提取日期和时间:
{ "id": 1, "time": { "date": "2019-06-12 11:51:22.000000", "timezone_type": 3, "timezone": "UTC" }, "productCategory": "some cat", "kitchen": { "house": { "id": 555, "name": "bigHouse" }, "id": 55, "name": "smallKitchen", "country": "US" } }
我目前是这样做的:
<tr v-for="(cabinet, i) in cabinets">
<td>{{ cabinet.kitchen.id }}</td>
<td>{{ cabinet.productCategory }}</td>
<td>{{ getDate(cabinet.time.date) }}</td>
<td>{{ getTime(cabinet.time.date) }}</td>
</tr>
<script>
const axios = require('axios');
export default {
name: "Cabinets",
data() {
return {
bedroom : this.$session.get('bedroom').id,
cabinets: []
}
},
mounted() {
axios({
method: 'GET',
url: `/bedroom/${this.bedroom}/cabinets`
})
.then(response => {
this.cabinets = response.data
})
},
methods: {
getDate(datetime) {
return new Date(datetime).toISOString().slice(0,10);
},
getTime(datetime) {
return new Date(datetime).toISOString().slice(11,19);
}
}
}
</script>
日期没问题,但时间不行。返回日期和时间分别如下:2019-06-12
和 09:51:22
。时间应该是 11:51:22
。这可能是因为我在尝试获取时间时使用方法 Date()
但是当我尝试使用 Time()
时它给出了一个错误:
[Vue warn]: Error in render: "ReferenceError: Time is not defined".
但是,即使当时我能找到一个非常简单的修复方法,我真的不喜欢这种切片方式,我正在寻找可以为我做到这一点的方法,因为如您所见,切片字符串已经出现故障。
最佳答案
您收到该错误的原因是因为 JavaScript 中没有时间对象。
Date 的 toLocaleTimeString()
是一种更可靠的方法。
您可以在 getTime() 方法中使用它:new Date(dateTime).toLocaleTimeString()
。
请注意,toLocaleTimeString() 将显示用户计算机区域性指定的时间。
关于javascript - 另一种在转换为 ISO 字符串后不切片返回日期/时间的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271094/