moses toh
moses toh

Reputation: 13172

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

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?

Upvotes: 3

Views: 29158

Answers (3)

luiscla27
luiscla27

Reputation: 6419

The best way is to use the filter property of Vue and moment library:

Vue.filter('formatDate', function(value) {
  if (value) {
    return moment(String(value)).format('MM/DD/YYYY hh:mm')
  }
});

That way you can use a pipe to format every date that has been rendered:

<div>
    <p>{{ yourDate | formatDate}}</p>
</div>

For a more samples look at the following links:

Upvotes: 3

acdcjunior
acdcjunior

Reputation: 135762

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

Upvotes: 1

Charles Barnes
Charles Barnes

Reputation: 108

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
}

Upvotes: 1

Related Questions