问题
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