javascript - 另一种在转换为 ISO 字符串后不切片返回日期/时间的方法?

标签 javascript json vue.js vuejs2 vue-component

我有以下 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-1209: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() 将显示用户计算机区域性指定的时间。

You can override this behavior, though .

关于javascript - 另一种在转换为 ISO 字符串后不切片返回日期/时间的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271094/

相关文章:

javascript - 422 错误 Laravel ajax 表单在 Microsoft Edge 上发布

javascript - 如何在点击父div jquery时显示下一个div

javascript - 重建以 JSON 序列化的对象

javascript - 使用php和mysql进行日常统计

javascript - Highcharts : help to create the JSON

typescript - 自动生成的函数的Typesafe包装,然后仅通过使用 `__typename`作为参数来动态调用。 typescript

vue.js - Chrome 扩展 vue-devtools 未检测到 Vue

javascript - 如何配置 Laravel Mix Vue.js 源映射以在 Debug模式下显示真实的组件代码

javascript - node.js/javascript/couchdb 关联数组 View 似乎不起作用

javascript - 按钮在我的 HTML 的某些部分不起作用