How can I change format datetime to date in vue component?

筅森魡賤 提交于 2019-12-11 04:47:32

问题


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>

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

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

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

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

How can I solve this problem?


回答1:


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));



回答2:


You can get the Date by using toLocaleDateString().

If that does not output in the format that you would like then you will want to make your own string contcatenation by using the following

getDate(datetime) {

let date = new Date(datetime);

let dateString = `${date.getFullYear}/${date.getMonth() + 1}/${date.getDate}`

return date
}


来源:https://stackoverflow.com/questions/49619999/how-can-i-change-format-datetime-to-date-in-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!