如何在vue组件中将日期时间格式更改为日期? [英] How can I change format datetime to date in vue component?

查看:252
本文介绍了如何在vue组件中将日期时间格式更改为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Vue组件是这样的:

My vue component like this :

<template>
    ...
        <td>{{getDate(item.created_at)}}</td>
    ...

</template>
<script>
    export default {
        ...
        methods: {
            getDate(datetime) {
                let date = new Date(datetime).toJSON().slice(0,10).replace(/-/g,'/')
                return date
            }
        }
    }
</script>

如果我console.log(datetime),则结果为:2018-03-31 18:23:20

If I console.log(datetime), the result : 2018-03-31 18:23:20

我只想获取日期,并将格式更改为:2018年3月31日

I want to get only date and change the format to be : 31 Mar 2018

我尝试使用上面的组件,但结果如下:2018/03/31

I try like my component above, but the result like this : 2018/03/31

我尝试使用format方法和dateformat方法,但未定义

I try use format method and dateformat method, but it is undefined

我该如何解决这个问题?

How can I solve this problem?

推荐答案

没有lib的最佳方法实际上取决于您所针对的浏览器.请在下面查看一些可能性.

The best way without a lib really depends on the browser you target. See some possibilities below.

// IE 11 or later
function format(date) {
  var month = date.toLocaleString("en-US", { month: 'short' })
  return date.getDate() + ' ' + month + ' ' + date.getFullYear();
}
// Pretty much every browser
function formatCompat(date) {
  var ms = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return date.getDate() + ' ' + ms[date.getMonth()] + ' ' + date.getFullYear();
}

var d1 = new Date("2018-04-11T12:00:00.000Z");
console.log(format(d1));
console.log(formatCompat(d1));
var d2 = new Date("2010-01-01T12:00:00.000Z");
console.log(format(d2));
console.log(formatCompat(d2));

这篇关于如何在vue组件中将日期时间格式更改为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆